Skip to content

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.

18 min read0/4 questions

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:

JavaScript
const delay = (ms, value, fail = false) => new Promise((resolve, reject) => setTimeout(() => (fail ? reject(new Error(value)) : resolve(value)), ms)); const emails = ["ada@example.com", "sam@example.com", "not-an-email", "lin@example.com"];const send = (to) => delay(10, `sent to ${to}`, !to.includes("@")); const results = await Promise.allSettled(emails.map(send)); const sent = results.filter((r) => r.status === "fulfilled");const failed = emails.filter((_, i) => results[i].status === "rejected"); console.log(`${sent.length} sent, ${failed.length} failed`);console.log("retry these:", failed);
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputJavaScript

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(" "));
Need a nudge? Hints walk you through it.

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:

JavaScript
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); function withTimeout(promise, ms) { let timer; const timeout = new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(`timed out after ${ms} ms`)), ms); }); return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));} console.log(await withTimeout(sleep(20).then(() => "fast enough"), 100));try { await withTimeout(sleep(300).then(() => "too slow"), 100);} catch (e) { console.log(e.message);}
Output
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:

JavaScript
const attempt = (ms, name, ok) => new Promise((resolve, reject) => setTimeout(() => (ok ? resolve(name) : reject(new Error(`${name} down`))), ms)); console.log(await Promise.any([attempt(10, "mirror-a", false), attempt(30, "mirror-b", true)])); try { await Promise.any([attempt(10, "mirror-a", false), attempt(20, "mirror-b", false)]);} catch (e) { console.log(e.constructor.name, e.errors.map((err) => err.message));}
Output
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.

JavaScript
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); async function mapWithLimit(items, limit, fn) { const results = new Array(items.length); let next = 0; async function worker() { while (next < items.length) { const i = next++; // claim an index (safe: JS runs one line at a time) results[i] = await fn(items[i]); } } const workers = Array.from({ length: Math.min(limit, items.length) }, worker); await Promise.all(workers); return results;} let active = 0;let peak = 0;async function upload(file) { active++; peak = Math.max(peak, active); await sleep(10 + file.length); active--; return file.toUpperCase();} const files = ["a.png", "b.png", "c.png", "d.png", "e.png", "f.png", "g.png"];const out = await mapWithLimit(files, 3, upload);console.log(out.join(" "));console.log("most uploads at once:", peak);
Output
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.

A pool of 3 workers over time
t0t1t2
worker 1a
worker 2b
worker 3c

Three workers start, each claiming the next file. Files d to g wait their turn.

1/3

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.
JavaScript
function debounce(fn, ms) { let timer; return (...args) => { clearTimeout(timer); // cancel the previous plan timer = setTimeout(() => fn(...args), ms); };} function throttle(fn, ms) { let last = 0; return (...args) => { const now = Date.now(); if (now - last >= ms) { last = now; fn(...args); } };} const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));const search = debounce((q) => console.log("search:", q), 100);const onScroll = throttle((y) => console.log("scroll at", y), 100); for (const q of ["j", "ja", "jav", "java"]) { search(q); // typing quickly, 20 ms apart await sleep(20);}await sleep(150); for (let y = 0; y <= 500; y += 50) { onScroll(y); // an event every 30 ms for about a third of a second await sleep(30);}
Output
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:

HTML & CSS
<style> body { font-family: system-ui, sans-serif; padding: 16px; } input { font-size: 16px; padding: 8px; width: 100%; box-sizing: border-box; } p { margin: 8px 0; }</style><label for="q">Search recipes</label><input id="q" placeholder="Type quickly, then stop" autocomplete="off" /><p>Keystrokes: <strong id="keys">0</strong></p><p>Searches sent (debounced 400 ms): <strong id="sent">0</strong></p><p id="last">Last search: none</p><script> function debounce(fn, ms) { let timer; return (...args) => { clearTimeout(timer); timer = setTimeout(() => fn(...args), ms); }; } let keys = 0; let sent = 0; const runSearch = debounce((value) => { sent++; document.getElementById("sent").textContent = sent; document.getElementById("last").textContent = "Last search: " + (value || "(empty)"); }, 400); document.getElementById("q").addEventListener("input", (e) => { keys++; document.getElementById("keys").textContent = keys; runSearch(e.target.value); });</script>

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.

Predict the outputJavaScript

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");
Need a nudge? Hints walk you through it.
Match the pairs0/4 matched

Pick the pattern for each job.

Choose an item, then its match on the other side.

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".

Out-of-order responses
Search boxYour codeServertyped caGET ?q=catyped catGET ?q=catresults for catresults for ca

The first request starts.

1/6

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.

JavaScript
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); function fakeSearch(q, { signal } = {}) { const latency = q === "ca" ? 80 : 20; // the older query is slower return new Promise((resolve, reject) => { const timer = setTimeout(() => resolve([`${q}-result-1`, `${q}-result-2`]), latency); signal?.addEventListener("abort", () => { clearTimeout(timer); reject(new DOMException("aborted", "AbortError")); }); });} let screen = "";let controller; async function onInput(q) { controller?.abort(); // cancel the request we no longer care about controller = new AbortController(); try { const results = await fakeSearch(q, { signal: controller.signal }); screen = `${q}: ${results.join(", ")}`; } catch (e) { if (e.name !== "AbortError") throw e; // real errors still surface console.log(`dropped stale request for "${q}"`); }} onInput("ca");await sleep(5);onInput("cat");await sleep(150);console.log("screen shows ->", screen);
Output
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.

Quick check
Your search box is already debounced by 300 ms. Can a stale response still overwrite newer results?
Need a nudge? A hint rules out a wrong answer.

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:

JavaScript
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); let checks = 0;async function getJobStatus(id) { await sleep(5); checks++; return checks < 5 ? { id, state: "running" } : { id, state: "done", url: "/exports/42.csv" };} async function pollUntilDone(id, { startMs = 20, maxMs = 160, deadlineMs = 2000 } = {}) { const giveUpAt = Date.now() + deadlineMs; let wait = startMs; while (Date.now() < giveUpAt) { const job = await getJobStatus(id); if (job.state === "done") return job; if (job.state === "failed") throw new Error("job failed"); console.log(`still running, next check in ${wait} ms`); await sleep(wait); wait = Math.min(wait * 2, maxMs); // back off, but not forever } throw new Error("gave up waiting");} const job = await pollUntilDone("export-42");console.log("ready:", job.url);
Output
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:

  1. Await it, return it, or catch it. Every promise needs an owner.
  2. 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);
  3. Let the linter help. The typescript-eslint rule no-floating-promises flags promises that are neither awaited nor handled. Turn it on in TypeScript projects.
  4. Watch out for forEach. items.forEach(async (item) => { await save(item); }) looks like it waits, but forEach ignores the promises its callback returns. Every save floats, the line after it runs immediately, and errors vanish. Use for...of with await for one at a time, Promise.all(items.map(save)) for all at once, or the pool above for a limited number.
  5. Install a safety net. Browsers fire an unhandledrejection event on window when a rejection goes unhandled; Node emits process.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
});
Key terms
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.any rejects with when every input fails; its errors array lists each reason.