试图了解Ember JS的承诺

时间:2013-08-18 05:56:57

标签: javascript asynchronous ember.js promise rsvp.js

我一直在努力研究一个代码示例来了解承诺。但我似乎无法弄清楚如何处理回调并在以后获得“可用”值。

以下是我正在研究的两个相关的JSBin示例。用冗长的样式写出来模仿烘焙饼干。

没有异步的Ember JS

http://jsbin.com/iSacev/1/edit

纯粹的同步示例,以显示基本行为(故意使用基本对象模型)

Ember JS有异步和承诺

http://jsbin.com/udeXoSE/1/edit

尝试扩展第一个示例并实现方法,其中事情以延迟完成,并在稍后返回已完成的promise对象。

试图理解的概念:

  • 如何正确处理承诺,特别是Ember.RSVP.Promise并稍后获取一个对象。
  • 如何使用Ember.run.later方法代替setTimeout

1 个答案:

答案 0 :(得分:14)

  

如何正确处理承诺,特别是Ember.RSVP.Promise并稍后获取一个对象

好像你已经接近了这个想法,只需要对你的jsbin进行一些小改动就可以了解情况:

首先,不要将 promise 推送到数组上,而应将promise传递给then回调的值。在这种情况下,您根本不需要该承诺对象。所以:

// 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中的错误。在原始版本中,承诺被拒绝是因为条件测试总是评估为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

  

如何使用Ember.run.later方法代替setTimeout

它们基本上是一回事。你似乎正确使用它。

相关问题