Question:
Consider the following code where a list of deferred tasks is created:
var deferreds = getSomeDeferredStuff(); $.when(deferreds).done(function() { console.log("All done!") });
However, "All done!" is logged before all deferred tasks are completed. How can you pass an array of deferreds into $.when() and ensure that it waits for all tasks to finish?
Answer:
To pass an array of values to a function that expects separate parameters, use Function.prototype.apply:
$.when.apply($, deferreds).then(function() { console.log("All done!") });
Here's a breakdown of the code:
Alternatively, in ES6 and newer, you can use the spread operator:
$.when(...deferreds).then(function() { console.log("All done!") });
In either case, the handler will receive an array of results, one for each deferred. Process this array to obtain the values you need.
The above is the detailed content of How to Ensure $.when() Waits for All Deferred Tasks in an Array?. For more information, please follow other related articles on the PHP Chinese website!