jQuery.when(deferreds)或ZenDesk App中的等价物

时间:2013-09-05 16:09:07

标签: javascript jquery zendesk

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

  1. 从故障单和请求者中检索一些识别信息
  2. 向其他网络服务提出多项请求
  3. 使用合并结果修改故障单
  4. 使用普通jQuery,您可以使用jQuery.when(deferreds)进行协调,以便在步骤2中的所有请求完成后触发第3步:

    $.when($.ajax("/page1"), $.ajax("/page2"))
        .done(function(page1result, page2result) { 
            // modify the ticket with the results
        });
    
    1. 应用程序中是否有jQuery.when()? (我试了this.$.when()没有运气。)
    2. 如果没有,那么实现类似目标的首选方法是什么? (也许直接使用Promises?)

1 个答案:

答案 0 :(得分:5)

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

this.ajax(...)替换this.createPromise()来做实际工作。

app.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'
        }
    };
}());