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

ESV*_*ESV 4 javascript jquery zendesk

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

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

使用普通的jQuery,你可以使用jQuery.when(deferreds)协调它,一旦步骤2中的所有请求完成,就触发第3步:

$.when($.ajax("/page1"), $.ajax("/page2"))
    .done(function(page1result, page2result) { 
        // modify the ticket with the results
    });
Run Code Online (Sandbox Code Playgroud)
  1. 是否在应用程序中提供了jQuery.when()?(我试着this.$.when()没有运气.)
  2. 如果没有,那么完成类似事情的首选方式是什么?(也许直接使用Promises?)

ESV*_*ESV 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'
        }
    };
}());
Run Code Online (Sandbox Code Playgroud)