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 Deferred
s
Update:
I updated the code after lanzz mentioned that my contrived example already returns a Deferred, I updated my example to include doSomeWork