JQuery - $.when syntax for array of Deferred objects [duplicate]

瘦欲@ 提交于 2019-11-29 23:41:34

问题


It is the first time I am using $.when and I am having difficulty with the syntax.
I have code similar to simplified example below. It works (if I haven't caused an error when I simplified it). My problem is that I don't know home many elements the customerIds array would contain.

var customerIds = new [1, 2, 3];

$.when(
    getCustomerData(customerIds[0]),
    getCustomerData(customerIds[1]),
    getCustomerData(customerIds[2])
).then(function() {
    alert('success');
}).fail(function() {
    alert('error');
});

function getCustomerData(int id) {
    return new $.Deferred(function(defer) {
                    doSomeWork(id, defer);
    }).promise();       
}

I would like to write the $.when statement as follows but having difficulty getting the syntax right.

$.when(
    getCustomerDataCalls(customerIds),
).then(function() {
    alert('success');
}).fail(function() {
    alert('error');
});

Where getCustomerDataCalls is implemented as:

function getCustomerDataCalls(customerIds) {
    var dfds = [];

    for (var id in customerIds) {
        dfds.push(new $.Deferred(function(defer) {
                                    doSomeWork(id, defer);
                                 }).promise());     
    }

    return dfds;
}

Unfortunately something is wrong with my implementation and I cannot work out where I am going wrong. My best guess is that something is going wrong when returning an array of Deferreds

Update:
I updated the code after lanzz mentioned that my contrived example already returns a Deferred, I updated my example to include doSomeWork


回答1:


Yes, I have stumbled upon this as well: when does not easily allow to be passed an array. But you could use apply to achieve the desired result.

$.when.apply($, getCustomerDataCalls(customerIds))


来源:https://stackoverflow.com/questions/10893668/jquery-when-syntax-for-array-of-deferred-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!