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.allrejects as soon as any input rejects (fail-fast). The other requests keep running; their results are just ignored.Promise.allSettlednever rejects. It returns{ status, value | reason }for each input.- Sequential
awaits in a loop run one after another. Start them together andawait Promise.all(...)to run them in parallel. - An unhandled rejection doesn't crash the browser page, but it's a bug. Always
catchsomewhere. - Return or
awaitinsidetry; a Promise that isn't awaited escapes thecatch.
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.racevsPromise.any?racesettles with the first Promise to settle, success or failure (useful for timeouts).anyresolves with the first success and rejects only if all fail.- Does
fetchreject on a 404? No. It only rejects on network errors; checkresponse.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:
awaitinside aforEachloop, expecting it to wait.