简体   繁体   English

Ember-在闭包操作中返回嵌套诺言的响应

[英]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(); 问题是return user.save(); is now in the callback for query operation, and is not being returned from the submit action. 现在位于查询操作的回调中,并且未从Submit操作中返回。

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? 如何重组代码,以便查询许可证记录,然后将user.save()的结果返回到我的组件?

 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. then方法已经实现了从回调中获取结果的魔力 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();
//  ^^^^^^
  });
},

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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