jQuery.when(deferreds)或等价的ZenDesk应用程序中的内容

4
在我的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
    });
  1. jQuery.when()在应用程序中可用吗?(我尝试使用this.$.when()但没有成功。)
  2. 如果不可用,有什么更好的方法来实现类似的功能?(也许直接使用Promises?)

ZenDesk应用程序插件环境完全由ZenDesk定义。jQuery和Underscore会自动包含(http://developer.zendesk.com/documentation/apps/migration/introduction.html#use-of-jquery-and-prototype)。 - ESV
1个回答

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接