如何正确处理 Promise,特别是 Ember.RSVP.Promise 并稍后获取对象
看来您已经接近解决这个问题了,只需对您的 jsbin 进行一些小的更改即可使事情正常运行:
首先,不要推动promise到你的数组上,你应该将承诺传递给的值then
打回来。实际上,在这种情况下,您根本不需要该 Promise 对象。所以:
// Call the then function on the promise
App.cookieSlowBake(cookie).then(function(value) {
alert("Your slow baked cookies are ready to eat");
App.CookieStore.pushObject(value);
}, function(value) {
// failure
alert("Something happened with the oven sorry no cookies.");
});
第二个更改是修复 cookieSlowBake 中的错误。在原始版本中,promise 被拒绝,因为条件测试总是评估为 false,因为它不在 Ember.run.later 回调中。新版本摆脱了条件,只在回调完成时解决承诺。
var bakedCookiePromise = new Ember.RSVP.Promise(function(resolve, reject){
var bakeTime = 2000; // milliseconds
var bakedCookie = false;
Ember.run.later(cookieDough, function() {
// code here will execute within a RunLoop in about the bakeTime with this == cookieDough
cookieDough.set('deliveryStatus', "cookie delivered later after baking " + bakeTime);
bakedCookie = true;
resolve(cookieDough);
}, bakeTime);
});
请参阅此处的工作 jsbin:http://jsbin.com/ebOBEk/1/edit http://jsbin.com/ebOBEk/1/edit
如何使用 Ember.run.later 方法代替 setTimeout
它们基本上是同一件事。看来你使用它是正确的。