Backbone 与 Promise.js 或纯 jQuery 解决承诺

Backbone with Promise.js or pure jQuery to resolve promises

我要管理一个用 Backbone.js 制作的项目。该项目于2013年首次发布。目前我正在尝试弄清楚他们之前做了什么。

我发现他们经常使用 Promise.js libery 来与 ReST-Server 通信,就像下面的例子

run: function () {
    if (this.initialAppViewMethod) {
        Promise.resolve(this.model.get('session').fetch())
            .catch(this.showLoginView.bind(this))
            .then(this.initMainView.bind(this));
    }
},

我一直想知道他们使用 Promise.js 而不是已经使用的 jquery.js liberay 来做承诺是否有某种原因?

顺便说一句:如何转换此脚本以使用纯 jQuery 功能?

有人可能将 Promise.js 与 Backbone 一起使用的原因可能是为了与另一个库轻松集成,但没有代码,这只是推测。

作为:

Because jQuery "promises" are not pure?

这是 fixed in jQuery 3


Backbone async 在后台运行类似 fetch uses jQuery's ajax 的功能,它 returns 一个 jqXHR 对象。

The jQuery XMLHttpRequest (jqXHR) object returned by $.ajax() as of jQuery 1.5 is a superset of the browser's native XMLHttpRequest object.

[it] implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information).

此外,您可以直接使用 Backbone 异步函数回调和选项:

run: function () {
    if (this.initialAppViewMethod) {
        this.model.get('session').fetch({
            context: this,
            error: this.showLoginView,
            success: this.initMainView
        });
    }
},

这就够了。