Home > Web Front-end > JS Tutorial > How Can Promise.all() Handle Multiple Concurrent Asynchronous Operations?

How Can Promise.all() Handle Multiple Concurrent Asynchronous Operations?

Susan Sarandon
Release: 2024-12-30 05:45:15
Original
647 people have browsed it

How Can Promise.all() Handle Multiple Concurrent Asynchronous Operations?

Handling Multiple Asynchronous Operations Concurrently

In scenarios where a sequence of asynchronous operations (represented as Promises) are executed, it becomes necessary to determine when all these operations have completed before proceeding with subsequent tasks. This article provides a solution to this challenge by leveraging the Promise.all() method.

As you mentioned, the doSomeAsyncStuff() function performs asynchronous tasks. By modifying it to return a Promise, we can capture the completion status of each asynchronous operation. This allows us to collect all these Promises into an array, which is then passed to Promise.all().

The Promise.all() method accepts an array of Promises as its parameter. Once all the Promises in the array have either resolved or rejected, Promise.all() returns a single Promise. This single Promise resolves to an array of the results (or rejection reasons) from the individual Promises.

In your code, you can implement this by incorporating the following steps:

const promises = [];

// Create a Promise for each asynchronous operation
for (let i = 0; i < 5; i++) {
  promises.push(doSomeAsyncStuff());
}

// Use Promise.all to wait for all the Promises to resolve
Promise.all(promises)
  .then(() => {
    // All asynchronous operations have completed. Execute subsequent tasks here.
    for (let i = 0; i < 5; i++) {
      doSomeStuffOnlyWhenTheAsyncStuffIsFinish();
    }
  })
  .catch((e) => {
    // Handle any errors that occurred during the asynchronous operations.
  });
Copy after login

By utilizing Promise.all(), you can effectively ensure that all asynchronous operations have completed successfully before executing tasks that depend on their results.

For further clarification, refer to the provided example:

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 here
    });
}

test();
Copy after login

In this example, we define an asynchronous function doSomethingAsync() that resolves with a random delay. We create an array of Promises and use Promise.all() to wait for all of them to resolve. Once they all complete successfully, we can proceed with our subsequent tasks.

The above is the detailed content of How Can Promise.all() Handle Multiple Concurrent Asynchronous Operations?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template