How do you use the Promise.allSettled() method in JavaScript?

The Promise.allSettled() method in JavaScript is a utility method that allows you to execute a set of promises and wait for all of them to be settled, regardless of whether they were fulfilled or rejected.

It returns a promise that resolves to an array of objects, where each object represents the outcome of each individual promise.

The Promise.allSettled() method is particularly useful when you need to perform multiple asynchronous operations and you want to know the outcome of each operation, even if some of them fail.

It was introduced in the ECMAScript 2020 (ES2020) specification and is supported in all modern browsers.

Syntax:

Promise.allSettled(iterable);

Here, iterable is an iterable object, such as an array or a string, that contains a list of promises.

The method returns a promise that resolves to an array of objects, where each object has the following properties:

Example Usage:

Consider the following example where we have an array of promises that perform some asynchronous operations and we want to know the outcome of each promise:

const promises = [
  Promise.resolve("foo"),
  Promise.reject(new Error("bar")),
  Promise.resolve("baz"),
];

Promise.allSettled(promises)
  .then((results) => {
    results.forEach((result) => {
      console.log(result.status, result.value, result.reason);
    });
  })
  .catch((error) => {
    console.log(error);
  });

In this example, we create an array of three promises. The first and third promises are fulfilled with the values “foo” and “baz” respectively, while the second promise is rejected with an error message “bar”.

We then pass the array of promises to the Promise.allSettled() method and wait for all of them to settle. The then() method is called once all the promises are settled and it receives an array of objects that represent the outcome of each promise.

In the then() method, we iterate over the array of results and log the status, value, and reason properties of each object to the console. The output of this example will be as follows:

fulfilled "foo" undefined
rejected undefined Error: bar
fulfilled "baz" undefined

As we can see from the output, the Promise.allSettled() method returns an array of objects, where each object represents the outcome of each promise, regardless of whether it was fulfilled or rejected.

Benefits of using Promise.allSettled():

Thank you for reading, and let’s have conversation with each other

Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.

Read more: