乐闻世界logo
搜索文章和话题

Wait for multiple promises to finish

1个答案

1

In JavaScript, when you need to wait for multiple Promises to complete, there are several methods to achieve this:

1. Promise.all()

This is one of the most commonly used methods, particularly suitable when all asynchronous operations must succeed before proceeding to the next steps. Promise.all() accepts an array of Promise objects as a parameter. When all the Promises have successfully resolved, it returns a new Promise. This new Promise resolves asynchronously, and its result is an array containing the results of all the input Promises.

Example:

javascript
let promise1 = Promise.resolve(3); let promise2 = 42; let promise3 = new Promise((resolve, reject) => { setTimeout(resolve, 100, 'foo'); }); Promise.all([promise1, promise2, promise3]).then(values => { console.log(values); // Output: [3, 42, "foo"] }).catch(error => { console.log('a Promise has failed:', error); });

2. Promise.allSettled()

Promise.allSettled() was introduced in ES2020. Unlike Promise.all(), Promise.allSettled() waits for all input Promises to be settled (either resolved or rejected). The returned Promise always resolves successfully, and its result is an array where each object represents the result of the corresponding Promise, whether it was fulfilled or rejected.

Example:

javascript
let promise1 = Promise.resolve(3); let promise2 = new Promise((resolve, reject) => { setTimeout(reject, 100, 'rejected'); }); Promise.allSettled([promise1, promise2]).then(results => { results.forEach((result) => { console.log(result.status); // "fulfilled" or "rejected" }); });

3. Promise.race()

Promise.race() is used to return the result of the fastest Promise among multiple Promises, regardless of whether it is resolved or rejected. It only returns the result of the first completed Promise.

Example:

javascript
let promise1 = new Promise((resolve, reject) => { setTimeout(resolve, 500, 'one'); }); let promise2 = new Promise((resolve, reject) => { setTimeout(resolve, 100, 'two'); }); Promise.race([promise1, promise2]).then(value => { console.log(value); // "two" - the first resolved Promise });

Summary

  • Use Promise.all() when you need all asynchronous operations to succeed.
  • Use Promise.allSettled() to handle the results of all Promises after they complete, regardless of success or failure.
  • Use Promise.race() to obtain the fastest result, whether successful or not.

These methods provide flexibility for handling multiple Promises in different scenarios.

2024年6月29日 12:07 回复

你的答案