【发布时间】: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