JQuery - $ .when syntax for an array of deferred objects

This is the first time I use $.when and I am having syntax difficulties.
I have code similar to a simplified example below. It works (unless I caused an error when I simplified it). My problem is that I do not know how many elements the customerIds array contains.

 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 as follows, but with the difficulty of getting the syntax correctly.

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

Where getCustomerDataCalls 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 figure out where I am going wrong. It’s best to assume that something is wrong when you return the Deferred s array

Update:
I updated the code after lanzz mentioned that my far-fetched example already returns Delayed, I updated my example by including doSomeWork

+3
source share
1 answer

Yes, I also stumbled upon this: when doesn't just let you pass an array. But you can use apply to achieve the desired result.

 $.when.apply($, getCustomerDataCalls(customerIds)) 
+15
source

All Articles