lundi 26 février 2018

Ember- return the response from a nested promise in a closure action

Using the pattern below I can return the result of a save operation in my route to a component, using closure actions. This works fine.

Route

actions: {
    submit: function(values) {
      var user = this.store.createRecord('user', values);
      return user.save();
    },
  }

Component

this.attrs.submit(values).then((response) => {
  //Handle success
}).catch(error => {
  //Handle error
});

In my submit action, I would like to first fetch the license object that the user belongs to and then set that on the user object before saving, as below.

The problem is that return user.save(); is now in the callback for query operation, and is not being returned from the submit action.

How can I restructure my code so that I can query the license record, and then return the result of user.save() to my component?

submit: function(values) {
  var user = this.store.createRecord('user', values);
  this.get('store').query('license', {
    filter: {
      code: values.licenseCode
    }
  }).then(function(licenses) {
    var license = licenses.get("firstObject");
    user.set('license', license);
    return user.save();
  });
},



Aucun commentaire:

Enregistrer un commentaire