【问题标题】:Two BackboneJS fetches and data gets swapped两次 BackboneJS 获取和数据被交换
【发布时间】:2015-10-04 04:21:48
【问题描述】:

这是我们在单个函数中的代码。我刚刚开始使用 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 有奇怪的行为”。

【问题讨论】:

  • 您能否描述一下您的数据的实际问题?什么是混合?这段代码稍微定义了代码执行的顺序——第三部分不一定是第一部分。承诺并不奇怪,它们很酷:)
  • 当这个。 mobilePromise 完成后,我们调用另一个函数来获取移动所需的更多信息。但是,我想知道为什么属性值来自 desktopPromise。我在 this.mobilePromise 的 .done 中添加了一个断点。它不会经常发生,但它会发生。
  • 可能第三个块有时可以在第二个块之前运行。您在第三个中是否有任何数据更改逻辑?我会继续回答提供一些代码。

标签: jquery backbone.js promise marionette


【解决方案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 将在 promise 解决后运行。您可以返回另一个承诺表单“做你的移动工作”部分,以延迟执行第三部分:

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

【讨论】:

    猜你喜欢
    • 2012-07-16
    • 2013-02-09
    • 2017-08-03
    • 2018-08-15
    • 2021-03-28
    • 1970-01-01
    • 2021-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多