SyntaxStudy
Sign Up
JavaScript Promise.all(), race(), allSettled(), any()
JavaScript Advanced 9 min read

Promise.all(), race(), allSettled(), any()

Promise Combinators

When you have multiple asynchronous operations to coordinate, running them sequentially with multiple await statements wastes time. JavaScript provides static promise combinator methods that manage multiple promises concurrently with different settlement strategies.

Promise.all(iterable)

Waits for all promises to fulfil and returns an array of results in the same order. If any promise rejects, the whole Promise.all immediately rejects with that error — a "fail fast" strategy.

Promise.allSettled(iterable)

Waits for all promises to settle (fulfil or reject) and returns an array of result objects with a status field. Use this when you need all results regardless of individual failures.

Promise.race(iterable)

Settles as soon as the first promise settles (either way). Useful for implementing timeouts.

Promise.any(iterable)

Fulfils as soon as the first promise fulfils. Rejects only if all promises reject (with an AggregateError). Use for "first success wins" strategies like trying multiple CDN mirrors.

Example
async function demo() {
  const p1 = fetch('https://jsonplaceholder.typicode.com/posts/1').then(r => r.json());
  const p2 = fetch('https://jsonplaceholder.typicode.com/posts/2').then(r => r.json());
  const [post1, post2] = await Promise.all([p1, p2]);
  console.log(post1.title, post2.title);
  const results = await Promise.allSettled([
    Promise.resolve('ok'),
    Promise.reject(new Error('fail'))
  ]);
  results.forEach(r => console.log(r.status, r.value || r.reason));
  function timeout(ms) {
    return new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), ms));
  }
  try {
    const data = await Promise.race([p1, timeout(5000)]);
    console.log(data);
  } catch (e) { console.error(e.message); }
}
demo();
Pro Tip

Use Promise.all() to run independent async operations concurrently rather than sequentially — three 1-second operations run concurrently finish in ~1 second, not 3 seconds.