Home >Web Front-end >JS Tutorial >How Can I Correctly Handle Arrays of Deferreds with jQuery's $.when()?
Handling Arrays of Deferreds in $.when()
When working with arrays of Deferred promises, it's important to know how to handle them when passing them into $.when(). In this article, we will delve into an issue where an array of Deferreds is not handled correctly by $.when() and provide a solution.
The Problem
Consider the following code:
function getSomeDeferredStuff() { var deferreds = []; for (i = 1; i <= 10; i++) { var count = i; deferreds.push( $.post('/echo/html/', { html: '<p>Task #' + count + ' complete.', delay: count }).success(function(data) { $("div").append(data); })); } return deferreds; } $(function() { $("a").click(function() { var deferreds = getSomeDeferredStuff(); $.when(deferreds).done(function() { $("div").append('<p>All done!</p>'); }); }); });
In this example, "All done!" should appear after all deferred tasks have completed. However, $.when() doesn't recognize the array of Deferreds as a single entity, resulting in "All done!" being displayed prematurely.
The Solution
To pass an array of Deferreds to $.when(), use Function.prototype.apply:
$.when.apply($, my_array).then( ___ );
This function takes an array of parameters and applies them to a function. For example:
$.when.apply($, deferreds).then(function() { $("div").append('<p>All done!</p>'); });
Alternatively, in ES6 you can use the spread operator:
$.when(...my_array).then( ___ );
The above is the detailed content of How Can I Correctly Handle Arrays of Deferreds with jQuery's $.when()?. For more information, please follow other related articles on the PHP Chinese website!