0

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();
  });
},
AJP
  • 515
  • 2
  • 13

1 Answers1

0

No restructuring necessary. The then method already does this magic of getting you the result from the callback. You just need to return the promise it gives you:

submit: function(values) {
  var user = this.store.createRecord('user', values);
  return this.get('store').query('license', {
//^^^^^^
    filter: {
      code: values.licenseCode
    }
  }).then(function(licenses) {
//  ^^^^^
    var license = licenses.get("firstObject");
    user.set('license', license);
    return user.save();
//  ^^^^^^
  });
},
Bergi
  • 630,263
  • 148
  • 957
  • 1,375