April 6, 2023

TypeScript - Promise.allSettled()

The Promise.allSettled() method is one of the promise concurrency methods. It takes an iterable of promises as input and returns a single Promise. This returned promise fulfills when all of the input's promises settle, with an array of objects that describe the outcome of each promise.

The result(object) returned by each input promise has the following properties:
  • status: A string, indicating the eventual state of the promise (either "fulfilled" or "rejected").
  • value: if status is "fulfilled". The result/value of the promise.
  • reason: if status is "rejected". The reason for promise rejection.

Promise.allSettled() is typically used when you have multiple asynchronous tasks that are not dependent on one another to complete successfully, and we like to know the result of each promise.

Lets see an example:

const p1 = 10;
const p2 = Promise.resolve(20);
const p3 = Promise.reject("some error");
const p4 = new Promise((resolve, reject) => {
  setTimeout(() => {
	resolve("value from promise4");
  }, 100);
});

Promise.allSettled([p1, p2, p3, p4])
.then((results) => {
  console.log(results);
});

Output will be :

[
  { status: 'fulfilled', value: 10 },
  { status: 'fulfilled', value: 20 },
  { status: 'rejected', reason: 'some error' },
  { status: 'fulfilled', value: 'value from promise4' }
]

Promise.allSettled() executes .then() for all the input promises regardless of the status of promise (either rejected or fulfilled). You can inspect the result object to find status, value and reason properties.

References:

Related Post(s):

1 comment: