Promise Combinators: Juggling Many Promises

Promise Combinators: Juggling Many Promises in JavaScript: is perfect for one task at a time.

Concept Explanation

async/await is perfect for one task at a time. But what if you need three API calls at once? Awaiting them one by one is slow — each waits for the last to finish. Promise combinators run many promises together and combine their results.

The four you'll actually use:

  • Promise.all — wait for all to succeed; reject the instant one fails.
  • Promise.allSettled — wait for all to finish, success or failure, and report each.
  • Promise.race — settle as soon as the first one settles (win or lose).
  • Promise.any — resolve with the first success, ignoring the failures.

Syntax or Core Structure

Run in parallel with Promise.all

// Sequential: ~3 seconds total (slow)
const user = await getUser();
const posts = await getPosts();
const stats = await getStats();

// Parallel: ~1 second total (fast)
const [user, posts, stats] = await Promise.all([
  getUser(), getPosts(), getStats()
]);

Survive partial failure with allSettled

const results = await Promise.allSettled([apiA(), apiB(), apiC()]);
results.forEach(r => {
  if (r.status === "fulfilled") console.log(r.value);
  else console.warn("Failed:", r.reason);
});

Real World Example

A dashboard that loads your profile, notifications, and recent orders should fire all three requests at once with Promise.all, not one after another. Promise.race powers timeouts too: race your fetch against a "reject after 5s" promise, and whichever finishes first wins.


Common Mistakes

  1. Promise.all is all-or-nothing: one rejected promise throws away every result. Use allSettled when partial success is acceptable.
  2. Awaiting inside a loop: for (const id of ids) await fetch(id) runs them one at a time. Map to promises and Promise.all the array instead.
  3. Passing references, not calls: combinators need an array of promises, so call the functions — getUser(), not getUser.

Best Practices

  • Parallel by default: if tasks don't depend on each other, run them together.
  • Pick the right combinator: need every result -> all; need a report of each -> allSettled; need the fastest -> race/any.
  • Always handle rejection: wrap Promise.all in try/catch, or an unhandled rejection can crash Node.

Practice Exercises

  1. The Parallel Loader: Fetch three JSONPlaceholder resources with Promise.all and log all three once they're ready.
  2. The Resilient Batch: Use Promise.allSettled on a mix of good and bad URLs and print which ones succeeded.
  3. The Timeout: Use Promise.race to reject a fetch if it takes longer than 2 seconds.