两次 BackboneJS 获取和数据交换

Two BackboneJS fetches and data gets swapped

这是我们在单个函数中的代码。我刚刚开始使用 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 告诉我,"promises have weird behaviors".

让我们稍微重写一下

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 将在承诺解决后运行。您可以 return 另一个承诺形式 "do your mobile stuff" 部分来延迟第三部分的执行:

this.mobilePromise = this.mobile.fetch()
    .then(function(){
        // do your mobile stuff
        var moreMobileDetails = new MoreMobileDetails();
        return moreMobileDetails.fetch();
    }.bind(this))