Async JavaScript
Asynchronous JavaScript is not about doing many things at once — it is about not waiting. The
progression from callbacks to promises to async/await is a progression in composability: each
step makes it easier to sequence, parallelise and cancel work.
The 60-second answer
Section titled “The 60-second answer”“Callbacks work but invert control: you hand your continuation to someone else and lose the ability
to compose, cancel or catch errors uniformly. A promise is a placeholder for a future value with
three states — pending, fulfilled, rejected — and it is chainable because then returns a new
promise. async/await is syntax over promises: try/catch and reading order, with the same
scheduling. For concurrency use Promise.all when every result is required, allSettled when
partial success is acceptable, race for the first to settle, any for the first to succeed.
Cancellation is not built into promises; you pass an AbortSignal into the API doing the work.”
Callbacks, briefly
Section titled “Callbacks, briefly”The error-first callback convention works, but control is inverted: the library decides when and how often to call you, and errors are threaded by hand through every level. Promises fix “many times” by settling once, and fix composition by being values you can pass around.
Promises
Section titled “Promises”fetch('/api/user') .then((res) => { if (!res.ok) throw new Error(`HTTP ${res.status}`); return res.json(); }) .then((user) => console.log(user.name)) .catch((err) => console.error('failed:', err)) .finally(() => hideSpinner());Semantics interviewers probe: a promise settles once, so later resolve/reject calls are
ignored; .then returns a new promise, so chains are values; returning a promise from then
flattens it; throwing inside then rejects the next promise (.catch(fn) is .then(undefined, fn));
and an unhandled rejection surfaces globally via unhandledrejection.
async/await
Section titled “async/await”async function loadUser(id: string): Promise<User> { const res = await fetch(`/api/users/${id}`); if (!res.ok) throw new Error(`HTTP ${res.status}`); return res.json() as Promise<User>;}
try { render(await loadUser('42')); }catch (err) { if (err instanceof Error) showError(err.message); }await only works inside async functions or at a module’s top level. It pauses the function,
not the program: the caller gets a promise immediately. An async function always returns a
promise, so a thrown error becomes a rejection, not a synchronous exception.
The four combinators
Section titled “The four combinators”all fails fast and requires every result; allSettled never rejects and returns a status per
item; race settles with the first outcome either way; any resolves with the first success and
rejects with an AggregateError only if all fail.
const [user, posts] = await Promise.all([fetchUser(), fetchPosts()]);
const results = await Promise.allSettled([a(), b(), c()]);const failures = results.filter((r) => r.status === 'rejected');Promise.all cancels nothing on failure — the other requests keep running. Promise.all([])
resolves immediately with [], and it accepts any iterable of thenables.
Sequential versus parallel
Section titled “Sequential versus parallel”// Sequential: each await waits for the previous round trip.for (const id of ids) results.push(await fetchItem(id));
// Parallel: all in flight at once, when the set is small.const results = await Promise.all(ids.map(fetchItem));Use sequential when the next call depends on the previous result or you must respect a rate limit;
use parallel when the calls are independent. For large sets, cap concurrency with a worker pool
(p-limit, or limit workers pulling from a queue) so you do not open 1,000 sockets at once. await
inside forEach does nothing useful — forEach ignores returned promises — so it fires everything at
once and finishes before any of it completes.
Cancellation with AbortController
Section titled “Cancellation with AbortController”Promises have no cancel. The modern answer is a signal the operation itself observes.
const controller = new AbortController();try { const res = await fetch('/api/search?q=js', { signal: controller.signal }); render(await res.json());} catch (err) { if (err instanceof DOMException && err.name === 'AbortError') return; throw err;}- Timeout:
AbortSignal.timeout(5000)fires on its own; combine withAbortSignal.any([a.signal, b.signal]). - Cleanup: in React, abort in the effect’s cleanup to avoid setting state after unmount.
- Non-fetch APIs: check
signal.abortedand listen for'abort'in your own async code.
Follow-up questions
Section titled “Follow-up questions”- Why does
Promise.allnot cancel the others when one fails? - How do you implement a retry with exponential backoff and a timeout?
- How would you bound concurrency for 1,000 URLs?
Common traps
Section titled “Common traps”awaitin a loop for independent work. It serialises what could be parallel.- No
returninsidethen. The chain proceeds withundefined. new Promisearound an existing promise API. It is an anti-pattern and loses cancellation.- Catching too broadly. A big
catchhides programming errors as network failures. - Forgetting to
awaitthe last call. A floating promise means errors escape.