Lesson 28 of 50Async JavaScript
Async Patterns
Real-world async recipes: partial failures, concurrency limits, debounce and throttle, cancelling stale requests, polling, and never losing an error.
You now know promises, async/await and fetch. That is the grammar. This lesson is the phrasebook: the handful of patterns that show up again and again in real apps. A search box that should not fire a request on every keystroke. An import job that must upload 500 files without opening 500 connections at once. A results list that sometimes shows the answer to an old query. A background job you check on every few seconds. Each one has a small, well-known solution, and each one is a favourite interview question because getting it wrong produces bugs that only appear on slow networks.
Every runnable block below uses fake async functions built from setTimeout, so you can see the timing without touching a network.
Combinators in practice
The previous lessons introduced Promise.all, allSettled, race and any. Here is how they look in day-to-day code, where the interesting part is what you do with the result.
allSettled: report partial failure
When you send a batch of independent jobs, one bad item should not hide the 49 that worked. Promise.allSettled gives you one result object per input, in input order, each with a status of "fulfilled" (plus value) or "rejected" (plus reason). Because the order matches the input, you can line results up with the items that produced them:
Press Run (⌘ Enter) to see what happens.What does this print?
const r = await Promise.allSettled([
Promise.reject(new Error("x")),
Promise.resolve(1),
]);
console.log(r.map((x) => x.status).join(" "));race: a reusable timeout
Promise.race settles with whichever promise settles first. Racing real work against a timer gives you a timeout for any promise, not just fetch. Clear the timer afterwards so it does not keep running for nothing:
Press Run (⌘ Enter) to see what happens.One honest caveat: a race only stops waiting. The slow work keeps running in the background. If the work supports an AbortSignal (like fetch), cancel it too.
any: first success wins
Promise.any fulfils with the first success and ignores failures until every input has failed. Then it rejects with an AggregateError whose errors array holds each reason, which is exactly what you want to log:
Press Run (⌘ Enter) to see what happens.Limiting concurrency
Promise.all(items.map(upload)) starts every upload at once. For 5 items that is fine. For 5,000 it can trip a server's rate limit, run out of sockets, or freeze a phone. The fix is a pool: a fixed number of workers that each take the next item when they finish their current one. At most limit tasks are ever in flight.
Press Run (⌘ Enter) to see what happens.Two details make this work. next++ is safe without locks because JavaScript runs one piece of code at a time (the event loop lesson): no two workers can claim the same index. And storing by i keeps results in input order, just like Promise.all. Libraries such as p-limit package this idea, but the ten lines above are worth knowing by heart.
How big should the limit be? There is no magic number. Browsers already cap connections per server (around six for HTTP/1.1), and many APIs document a rate limit, so 3 to 10 is a common starting point; measure, then adjust. Also decide what one failure means. In this version, a rejected fn rejects Promise.all(workers) and the caller sees the error, but the other workers keep going. If you want every outcome instead, catch inside the worker and store { ok: false, error } in results[i], the same idea as allSettled.
Three workers start, each claiming the next file. Files d to g wait their turn.
Debounce and throttle
Some events fire far more often than you want to react to them. A user typing "javascript" fires 10 input events; scrolling fires dozens per second. Two wrappers tame them:
- Debounce: wait until the events stop for
ms, then run once with the latest value. Perfect for search-as-you-type, autosave, and resize handlers that recalculate layout. - Throttle: run at most once every
ms, no matter how many events arrive. Perfect for scroll position tracking, drag handlers, and "load more when near the bottom" checks, where you want steady updates during the activity.
Press Run (⌘ Enter) to see what happens.The debounced search runs once, with the final query. The throttled handler runs a few times, spread out, instead of eleven. Try it with a real input box. The counter shows how many requests you saved:
Preview
Change 400 to 50 and type at your normal speed: the saving mostly disappears. Debounce delays of 200 to 400 ms feel responsive for search.
What does this print?
function debounce(fn, ms) {
let t;
return (...a) => { clearTimeout(t); t = setTimeout(() => fn(...a), ms); };
}
const log = debounce((q) => console.log("search", q), 100);
log("c"); log("ca"); log("cat");Pick the pattern for each job.
Cancelling stale requests
Here is a bug that passes every test on a fast laptop. A user types "ca", then "cat". Two requests go out. The server happens to answer "cat" first and "ca" second. Your code renders whatever arrives last, so the screen now shows results for "ca" while the box says "cat".
The first request starts.
Debounce reduces how often this happens but cannot prevent it. The fix is latest wins: when a new request starts, abort the previous one with an AbortController. An aborted request rejects with an AbortError, which you ignore because it is not a real failure.
Press Run (⌘ Enter) to see what happens.Delete the controller?.abort() line and run it again: the screen ends up showing ca. When an API cannot be cancelled, the same idea works with a counter: give each request an id and only render a response whose id is still the latest. React's data libraries (TanStack Query, SWR) do this for you, which is one reason teams use them.
Polling with backoff
Some work takes too long for one request: a video transcode, a report export, a payment that needs confirmation. The API returns a job id, and you poll: ask "is it done yet?" until it is. Checking every 100 ms wastes the server's time; checking every minute makes users wait. Start fast and slow down, with a cap and an overall deadline:
Press Run (⌘ Enter) to see what happens.This differs from the retry loop you saw before. Retrying repeats a call that failed; polling repeats a call that succeeded but reported "not yet". In a component, stop polling when the user leaves the page (abort, or clear a flag), and prefer a push channel (WebSockets, server-sent events) when updates must be instant.
Some APIs expose progress as an async iterable, and for await...of (from the previous lesson) reads it one update at a time. A polling loop is easy to wrap as an async function* that yields each status, so the caller writes for await (const status of watchJob(id)).
Never lose an error
The most dangerous async bug produces no error at all. A floating promise is one that nobody awaits, returns or attaches a .catch to:
async function onSave() {
saveDraft(form); // floating: if it rejects, nobody hears about it
showToast("Saved"); // and this lies to the user
}Rules that keep errors visible:
- Await it, return it, or catch it. Every promise needs an owner.
- Fire and forget on purpose: if you really do not want to wait, attach a handler and mark the intent:
void sendAnalytics(event).catch(reportError); - Let the linter help. The typescript-eslint rule
no-floating-promisesflags promises that are neither awaited nor handled. Turn it on in TypeScript projects. - Watch out for
forEach.items.forEach(async (item) => { await save(item); })looks like it waits, butforEachignores the promises its callback returns. Every save floats, the line after it runs immediately, and errors vanish. Usefor...ofwithawaitfor one at a time,Promise.all(items.map(save))for all at once, or the pool above for a limited number. - Install a safety net. Browsers fire an
unhandledrejectionevent onwindowwhen a rejection goes unhandled; Node emitsprocess.on("unhandledRejection"). Use them to report to your error tracker, not as your main error handling.
window.addEventListener("unhandledrejection", (event) => {
reportToErrorTracker(event.reason); // send it somewhere a human will see
});- concurrency limit
- A cap on how many async tasks run at the same time, usually enforced with a pool of workers.
- debounce
- Delay a function until calls stop for a set time, then run it once with the latest arguments.
- throttle
- Run a function at most once per time window, however often it is called.
- stale response
- A reply to an outdated request that arrives after a newer one and overwrites the right data.
- polling
- Repeatedly asking a server whether a long job has finished, ideally with growing waits and a deadline.
- floating promise
- A promise that is not awaited, returned or caught, so its errors disappear.
- AggregateError
- The error
Promise.anyrejects with when every input fails; itserrorsarray lists each reason.