CodePark/ questions / Promises & async/await
START PRACTICINGPRACTICE
Frontend question · JavaScript › Promises & async/await

Compare Promise.all, Promise.allSettled, Promise.race and Promise.any.

All four take an iterable (for example an array) of promises and return one promise. They differ in when that promise settles.

Promise.all:

  • It fulfills when all promises fulfill. The result is an array of values in the same order as the input.
  • It rejects as soon as any one rejects. This is called fail-fast.
  • The other promises keep running. Their results are just ignored.
  • Use it when you need every result.

Promise.allSettled:

  • It never rejects. It waits for all promises to finish.
  • It gives an array of { status: 'fulfilled', value } or { status: 'rejected', reason } objects.
  • Use it when some failures are acceptable.

Promise.race:

  • It settles the same way as the first promise to settle, whether that one fulfilled or rejected.
  • A common use is a timeout: race the request against a timer.

Promise.any:

  • It fulfills with the first promise that fulfills, and ignores rejections.
  • It rejects only if all promises reject, with an AggregateError.
  • Use it to try several sources for the same data.

None of them cancel the promises that are still running.

  • all gives all values, or the first rejection (fail-fast).
  • allSettled always fulfills, with a status object for each promise.
  • race follows the first promise to settle, success or failure.
  • any gives the first success, and an AggregateError only if all reject.
  • None of them cancel the remaining promises.