3

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

Philip Fourie
  • 111,587
  • 10
  • 63
  • 83

1 Answers1

15

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))
Raphael Schweikert
  • 18,244
  • 6
  • 55
  • 75
  • It seems to me that when should provide this behavior by default -- i.e. if the first argument is an array and the second argument is a function then when all the stuff in the array is done, call the function with the array of results. As it is, when isn't very useful since if you know in advance just how many deferred calls there are you could easily write the code out yourself. – podperson Jun 18 '14 at 14:16