[英]Composing promises in Ember
我在Ember中编写承诺时遇到了一些问题(我猜)。 从以下的新手的错误#1 在这里我写道:
return $.getJSON('config.json', (data) => {
//some code here...
return data;
}).then(() => {
return this.get('store').findRecord('staffMember', 13);
}).then(record => {
console.log(record);
});
据我了解,第二then
只有当应该叫findRecord
得到解决,它应该显示检索到的记录。 相反,它在控制台中显示了承诺。 为什么?
您是jQuery和Ember(RSVP)承诺之间(某种程度)不兼容的受害者。
以下是约束:
这是问题的代码,带有一些注释:
return $.getJSON('config.json', (data) => {
//some code here...
return data; // a return from a direct callback is meaningless (though it doesn't matter here as `data` is not used later downstream).
}) // at this point, you have a jQuery promise.
.then(() => { // this is the jQuery promise's .then().
return this.get('store').findRecord('staffMember', 13); // this is an Ember.RSVP promise, which will be seen by the jQuery chain as data, not assimilated.
})
.then(record => {
console.log(record); // oh dear, `record` is actually a jQuery promise.
});
因此问题中描述的症状 - 在控制台中记录了一个承诺。
解决方法是确保将jQuery承诺返回到Ember.RSVP链中,而不是相反。
以下是编写代码的几种方法,主要区别在于语法 - 两者都应该有效:
return Ember.RSVP.Promise.resolve() // start the chain with a resolved Ember.RSVP promise.
.then(function() {
return $.getJSON('config.json'); // returned jQuery promise will be recognised as such and assimilated by the Ember.RSVP chain
})
.then(data => {
//some code here ...
return this.get('store').findRecord('staffMember', 13); // as expected, the returned RSVP promise will also be assimilated.
})
.then(record => {
console.log(record);
});
或者,稍微更加经济:
return Ember.RSVP.Promise.resolve($.getJSON('config.json')) // assimilate jQuery promise into Ember.RSVP
.then(data => {
//some code here ...
return this.get('store').findRecord('staffMember', 13); // returned RSVP promise will also be assimilated
})
.then(record => {
console.log(record);
});
注意:从jQuery 3.0开始,jQuery承诺承诺Promises / A +。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.