JavaScript · Question 5 of 50
Promises or async/await? How do you handle errors, and run things in parallel?
Async control flow, sequential against parallel, and error handling.
The answer
A promise is a value that arrives later: pending, then fulfilled or rejected. async/await is syntax on top of promises: an async function always returns a promise, and await pauses that function (not the whole thread) until the promise settles, so the code reads top to bottom.
Errors: a rejected await throws, so wrap it in try/catch; a .then() chain needs a .catch(). The usual performance mistake is awaiting independent calls one after another. Start them together with Promise.all (fails on the first rejection) or Promise.allSettled (waits for all and reports each).
// slow: one after the other
const user = await getUser(id)
const orders = await getOrders(id)
// fast: both at once
const [u, o] = await Promise.all([getUser(id), getOrders(id)])The picture
sequential: getUser ─────▶ getOrders ─────▶ time ≈ a + b
parallel: getUser ─────▶
getOrders ────────▶ time ≈ max(a, b)What happens to a rejected promise nobody catches?
Show the answer
It becomes an unhandled rejection: a console warning in the browser, and in Node 15 and later it crashes the process by default.