Sobes.tech
Middle+

What static Promise methods do you know besides Promise.resolve? How does Promise.all differ from Promise.allSettled?

sobes.tech AI

Answer from AI

In addition to Promise.resolve, there are other static methods of Promise:

  • Promise.reject(reason) — creates a promise that is immediately rejected with the specified reason.
  • Promise.all(iterable) — takes an array (or other iterable) of promises and returns a new promise that:
    • resolves when all promises in the array are successfully fulfilled, with an array of results.
    • rejects immediately if any of the promises is rejected.
  • Promise.allSettled(iterable) — takes an array of promises and returns a promise that resolves when all promises have settled (either fulfilled or rejected), with an array of objects describing the outcome of each promise (fulfilled or rejected).
  • Promise.race(iterable) — returns a promise that resolves or rejects as soon as the first promise in the iterable resolves or rejects.
  • Promise.any(iterable) — returns a promise that resolves with the result of the first successfully fulfilled promise, or rejects if all promises are rejected.

Difference between Promise.all and Promise.allSettled:

  • Promise.all rejects as soon as any promise is rejected, useful when all operations need to succeed.
  • Promise.allSettled waits for all promises to settle, regardless of their outcome, and provides a detailed report, which is useful for collecting results with error handling.

Example:

Promise.all([
  Promise.resolve(1),
  Promise.reject('error'),
  Promise.resolve(3)
]).catch(console.log); // Will output 'error'

Promise.allSettled([
  Promise.resolve(1),
  Promise.reject('error'),
  Promise.resolve(3)
]).then(console.log);
/* Will output:
[
  { status: 'fulfilled', value: 1 },
  { status: 'rejected', reason: 'error' },
  { status: 'fulfilled', value: 3 }
]
*/
What static Promise methods do you know besides… - sobes.tech