Skip to main content
07

Promises and async/await: error handling and Promise.all vs allSettled

MediumJavaScriptPromisesAsync

How do Promises and async/await handle errors, and when do you use Promise.all vs Promise.allSettled?

TL;DR

A Promise represents a future value and is pending, then fulfilled or rejected. async/await is syntax over Promises: an async function always returns a Promise, and await pauses it until the Promise settles. Errors are handled with .catch() or with try/catch around await. Use Promise.all when you need every result and one failure should fail the whole thing; use Promise.allSettled when you want every outcome, success or failure.

Key points

  • Promise.all rejects as soon as any input rejects (fail-fast). The other requests keep running; their results are just ignored.
  • Promise.allSettled never rejects. It returns { status, value | reason } for each input.
  • Sequential awaits in a loop run one after another. Start them together and await Promise.all(...) to run them in parallel.
  • An unhandled rejection doesn't crash the browser page, but it's a bug. Always catch somewhere.
  • Return or await inside try; a Promise that isn't awaited escapes the catch.

Example

js
// Parallel, fail-fast
try {
  const [user, orders] = await Promise.all([getUser(id), getOrders(id)])
} catch (err) {
  showError(err)
}

// Parallel, keep partial results
const results = await Promise.allSettled(urls.map((u) => fetch(u)))
const ok = results.filter((r) => r.status === 'fulfilled')

Common follow-ups

  • Promise.race vs Promise.any? race settles with the first Promise to settle, success or failure (useful for timeouts). any resolves with the first success and rejects only if all fail.
  • Does fetch reject on a 404? No. It only rejects on network errors; check response.ok.

What interviewers look for

Tip

Show the parallel vs sequential difference, and pick all vs allSettled based on whether partial results are useful.

  • Red flag: await inside a forEach loop, expecting it to wait.

Was this helpful?

Related questions