09 / 17

What is the purpose of `Promise.all()`, `Promise.race()`, `Promise.any()`, `Promise.allSettled()`?

At their core, both Promise.all() and Promise.race() are concurrency methods. They let you hand off multiple asynchronous tasks (like API requests, file reads, or timers) at the same time and control how you want to handle their results. The easiest way to think about them is that Promise.all() is a team effort, while Promise.race() is a competition.

Promise.all() takes an array of Promises and returns a new Promise that resolves with an array of resolved values from all the input Promises.
  1. 1

    Rejected: If any of the promise is rejected it returns single error object from that specific failed promise. (Any remaining or successful promises are ignored).

  2. 2

    Resolved: When every single promise succeeds it resolves, It returns an array of results in the exact same order as the input array (regardless of which one finished first).

Promise.race() takes an array of Promises and returns a Promise that resolves or rejects as soon as the first Promise in the array resolves or rejects.
  1. 1

    Resolvesd: fulfils when any of the promises are fulfilled, It returns the single value of that fastest promise.

  2. 2

    Rejects: rejects when any of the promises are rejected. Returns the single error object of that fastest promise.

Promise.allSettled():
  1. 1

    Resolves: When every single promise finishes (some can succeed, some can fail). It never rejects.

  2. 2

    Returns: An array of objects describing the outcome of each promise. Each object has a status. { status: "fulfilled/rejected", value: result }

  3. 3

    Even if every single input promise fails, Promise.allSettled() will still resolve with an array of rejection objects.

Promise.any(): It ignores rejections (failures) and hunts for the first success.
  1. 1

    Rejects: rejects when all of the promises are rejected. It returns An AggregateError object. You can access an array of all the individual errors using error.errors.

  2. 2

    Resolves: As soon as the first successful promise finishes. It returns the single value of that fastest successful promise. (It completely ignores any faster promises that failed).