Gor*_*ter 9 javascript asynchronous promise ember.js rsvp.js
我一直在努力研究一个代码示例来了解承诺.但我似乎无法弄清楚如何处理回调并在以后获得"可靠"值.
这是我正在研究的两个相关的JSBin示例.用冗长的样式写来模仿烘焙饼干.
Ember JS没有异步
http://jsbin.com/iSacev/1/edit
纯粹的同步示例来显示基本行为(故意使用基本对象模型)
Ember JS有异步和承诺
http://jsbin.com/udeXoSE/1/edit
尝试扩展第一个示例并实现方法,其中事情以延迟完成并且稍后返回履行的promise对象.
试图理解的概念:
Mik*_*tti 14
如何正确处理promises,特别是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.");
});
Run Code Online (Sandbox Code Playgroud)
第二个变化是修复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);
});
Run Code Online (Sandbox Code Playgroud)
请参阅这里的jsbin:http://jsbin.com/ebOBEk/1/edit
如何使用Ember.run.later方法而不是setTimeout
它们基本上是一回事.你似乎正确使用它.