Promise all vs allsettled vs race

Promise all vs allsettled vs race

The Promise.all method is a way to wait for multiple promises to complete. It takes an iterable (such as an array) of promises as input, and returns a new promise that resolves when all of the input promises have resolved. If any of the input promises are rejected, the returned promise is rejected as well.

Here's an example of how you might use Promise.all:

const p1 = Promise.resolve(1);
const p2 = Promise.resolve(2);
const p3 = Promise.resolve(3);

Promise.all([p1, p2, p3]).then(values => {
  console.log(values); // [1, 2, 3]
});

In this example, Promise.all returns a promise that resolves with an array of the resolved values of the input promises (in this case, [1, 2, 3]).

The Promise.allSettled method is similar to Promise.all, but it returns a promise that is always fulfilled, regardless of whether the input promises are fulfilled or rejected. The resolved value of the returned promise is an array of objects that represents the outcome of each input promise, with a status property that is either "fulfilled" or "rejected", and a value or reason property that is the resolved value or rejection reason of the input promise.

Here's an example of how you might use Promise.allSettled:

const p1 = Promise.resolve(1);
const p2 = Promise.reject(new Error("error"));
const p3 = Promise.resolve(3);

Promise.allSettled([p1, p2, p3]).then(results => {
  console.log(results); // [{ status: "fulfilled", value: 1 }, { status: "rejected", reason: Error("error") }, { status: "fulfilled", value: 3 }]
});

In this example, Promise.allSettled returns a promise that is fulfilled with an array of objects that represents the outcome of each input promise.

The Promise.race method is a way to wait for the first of multiple promises to complete. It takes an iterable (such as an array) of promises as input, and returns a new promise that resolves or rejects as soon as one of the input promises resolves or rejects. The resolved value or rejection reason of the returned promise is the same as the first input promise to resolve or reject.

Here's an example of how you might use Promise.race:

const p1 = new Promise(resolve => setTimeout(resolve, 1000, 1));
const p2 = new Promise(resolve => setTimeout(resolve, 500, 2));
const p3 = new Promise(resolve => setTimeout(resolve, 2000, 3));

Promise.race([p1, p2, p3])

  • Date: