我在Ember中编写承诺时遇到了一些问题(我猜)。继新秀错误#1之后 here我写道:
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
并且它应该显示检索到的记录。相反,它在控制台中显示了承诺。的为什么吗
答案 0 :(得分:3)
您是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 +。