簡體   English   中英

在Ember中作出承諾

[英]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)承諾之間(某種程度)不兼容的受害者。

以下是約束:

  • 一個jQuery承諾吸收另一個jQuery承諾。
  • Ember.RSVP承諾吸收另一個Ember.RSVP承諾。
  • Ember.RSVP承諾是Promises / A +兼容, 並將同化jQuery承諾。
  • jQuery承諾不會同化Ember.RSVP的承諾。 jQuery promise鏈將返回的A + promise視為數據。

這是問題的代碼,帶有一些注釋:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM