简体   繁体   中英

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(); }); }, 

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();
//  ^^^^^^
  });
},

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM