Home >Web Front-end >JS Tutorial >How to Ensure $.when() Waits for All Deferred Tasks in an Array?

How to Ensure $.when() Waits for All Deferred Tasks in an Array?

Linda Hamilton
Linda HamiltonOriginal
2024-12-11 02:41:191055browse

How to Ensure $.when() Waits for All Deferred Tasks in an Array?

Passing an Array of Deferreds to $.when()

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:

  • $.when.apply($, deferreds): Spreads the deferreds array into separate arguments for $.when().
  • then(function): Attaches a handler that runs when all deferreds are resolved.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn