Working with Multiple Promises Asynchronously
This article aims to address the challenges of executing multiple asynchronous tasks within loops and the need to ensure their completion before proceeding with subsequent tasks.
Imagine a scenario where a loop iterates over a set of tasks, each of which is executed asynchronously. Following the loop, another loop relies on the completion of the first loop's tasks. How can we achieve this coordination efficiently?
Promises provide an elegant solution to this problem. By returning a promise from doSomeAsyncStuff(), we can manage the asynchronous operations.
Promise.all() is a powerful method that accepts an array of promises and returns a single promise. This single promise resolves only when all the input promises resolve or any of them reject.
To accomplish our goal, we can leverage Promise.all() as follows:
const promises = []; for (let i = 0; i < 5; i++) { promises.push(doSomeAsyncStuff()); } Promise.all(promises) .then(() => { // Execute tasks that require all async tasks to finish }) .catch((e) => { // Handle errors });
In this implementation, we collect all the promises in an array and pass it to Promise.all(). Upon its resolution (or rejection), we proceed with the second loop's tasks.
The following example demonstrates the utilization of Promise.all() to wait for multiple asynchronous tasks to complete:
function doSomethingAsync(value) { return new Promise((resolve) => { setTimeout(() => { console.log("Resolving " + value); resolve(value); }, Math.floor(Math.random() * 1000)); }); } function test() { const promises = []; for (let i = 0; i < 5; i++) { promises.push(doSomethingAsync(i)); } Promise.all(promises) .then((results) => { console.log("All done", results); }) .catch((e) => { // Handle errors }); } test();
The above is the detailed content of How Can Promise.all() Efficiently Handle Multiple Asynchronous Tasks Before Proceeding to Subsequent Operations?. For more information, please follow other related articles on the PHP Chinese website!