4

在我的 ZenDesk 应用程序中,我:

  1. 从票证和请求者那里检索一些识别信息
  2. 向另一个 Web 服务发出多个请求
  3. 使用组合结果修改工单

使用普通的 jQuery,一旦步骤 2 中的所有请求都完成,您将使用jQuery.when(deferreds)来触发步骤 3:

$.when($.ajax("/page1"), $.ajax("/page2"))
    .done(function(page1result, page2result) { 
        // modify the ticket with the results
    });
  1. jQuery.when() 在应用程序中可用吗?(我试过this.$.when()没有运气。)
  2. 如果不是,那么完成类似事情的首选方法是什么?(也许直接使用Promises?)
4

1 回答 1

5

jQuery.when()可通过应用程序对象作为this.when(). 这是一个简单的示例(框架版本 0.5),它创建了几个琐碎的承诺(使用this.promise(),类似于jQuery.Deferred())然后等待它们成功/解决以调用第三个函数。

代替this.ajax(...)this.createPromise()实际工作。

应用程序.js

(function() {
    return {
        onActivate: function() {
            var promises = []

            promises.push(this.createPromise().done(function() {
                console.log('promise 1 done');
            }));

            promises.push(this.createPromise().done(function() {
                console.log('promise 2 done');
            }));

            this.when.apply(this, promises).done(function() {
                console.log('all promises done');
            });
        },

        // returns a promise that always succeeds after 1 sec.
        createPromise: function() {
            return this.promise(function(done, fail) { 
                setTimeout(done, 1000);
            });
        },

        events: {
            'app.activated': 'onActivate'
        }
    };
}());
于 2013-09-06T00:04:39.220 回答