Sobes.tech
Middle+

Tell about the Promise methods: Promise.all, Promise.allSettled, Promise.race, Promise.any — how do they differ from each other?

sobes.tech AI

Answer from AI

All these methods work with an array of promises but differ in behavior and results:

  • Promise.all(iterable) — waits for all promises to successfully complete and returns an array of results in the same order. If at least one promise is rejected, the entire Promise.all is rejected with that error.

  • Promise.allSettled(iterable) — waits for all promises to settle, regardless of their status (fulfilled or rejected). Returns an array of objects with fields {status: "fulfilled" | "rejected", value | reason} for each promise.

  • Promise.race(iterable) — returns the result of the first promise to settle (fulfilled or rejected). As soon as one promise settles, its result or error is returned.

  • Promise.any(iterable) — waits for the first successfully fulfilled promise and returns its result. If all promises are rejected, it returns an AggregateError with the errors of all promises.

Example:

const p1 = Promise.resolve(1);
const p2 = Promise.reject('error');
const p3 = new Promise(res => setTimeout(() => res(3), 100));

Promise.all([p1, p3])
  .then(console.log) // [1, 3]
  .catch(console.error);

Promise.allSettled([p1, p2])
  .then(console.log); // [{status: 'fulfilled', value: 1}, {status: 'rejected', reason: 'error'}]

Promise.race([p3, p1])
  .then(console.log); // 1 (p1 is faster)

Promise.any([p2, p3])
  .then(console.log) // 3 (first successful)
  .catch(console.error);