这是我们在单个函数中的代码。我用BackboneJS开始变得更好。
// let's pull desktop data
this.desktop = new desktopItemModel({device: 'desktop'});
this.desktopPromise = this.desktop.fetch();
// let's pull mobile data
this.mobile = new mobileItemModel({device: 'mobile'});
this.mobilePromise = this.mobile.fetch();
// I'm not sure if the previous developer was trying to implement similar to $q.all
this.allPromise = [desktopPromise, mobilePromise];
$.when(this.desktopPromise).done(_.bind(function() {
// do your desktop stuff
}, this));
$.when(this.mobilePromise).done(_.bind(function() {
// do your mobile stuff
}, this));
if (this.allPromise) {
$.when.apply($, this.allPromise).done(_.bind(function() {
// do your stuff here if desktop
....
// do your stuff here if mobile
....
}, this));
}
我注意到我们的变量中的数据有时会在桌面和移动设备之间混淆。来自api服务器的响应很好。我实际上怀疑API团队在调试我们的应用程序之前返回了错误的数据,这是我们的代码做了一些奇怪的事情。
如何对其进行重构,以便数据不会混淆?有人在irc告诉我,"承诺有奇怪的行为"。
答案 0 :(得分:1)
让我们重写一下
this.desktop = new desktopItemModel({device: 'desktop'});
this.desktopPromise = this.desktop.fetch()
.then(function(){
// do your desktop stuff
}.bind(this));
this.mobile = new mobileItemModel({device: 'mobile'});
this.mobilePromise = this.mobile.fetch()
.then(function(){
// do your mobile stuff
}.bind(this))
$.when(this.desktopPromise, this.mobilePromise)
.done(function() {
// do your stuff here if desktop
// do your stuff here if mobile
}.bind(this));
}
试试这个。承诺解决后将运行Done
。您可以返回另一个承诺表单"做您的移动设备"延迟执行第三部分的部分:
this.mobilePromise = this.mobile.fetch()
.then(function(){
// do your mobile stuff
var moreMobileDetails = new MoreMobileDetails();
return moreMobileDetails.fetch();
}.bind(this))