How to wait until all Promises complete even if some are rejected in JavaScript?

Estimated read time 1 min read

To wait until all Promises complete even if some are rejected in JavaScript, you can use the Promise.all method. The Promise.all method takes an array of Promises as an argument and returns a new Promise that resolves when all of the Promises in the array have resolved or rejects with the reason of the first rejected Promise.

Here’s an example:

const promises = [Promise.resolve(1), Promise.reject(new Error("error")), Promise.resolve(3)];

Promise.all(promises)
  .then(values => {
    console.log("All promises resolved:", values);
  })
  .catch(error => {
    console.error("A promise was rejected:", error);
  });

In this example, we have an array of 3 Promises, one of which is rejected. The Promise.all method is used to wait until all Promises complete, and the then method is used to log the resolved values when all Promises resolve. The catch method is used to catch and log the error if one of the Promises is rejected.

Note that in this example, the catch method will only be executed if one of the Promises is rejected. If all Promises resolve, the catch method will not be executed.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply