Lesson 27 of 50Async JavaScript
Async/Await and fetch
Write async code that reads top to bottom, run requests in parallel, and call APIs with fetch, timeouts and retries.
This is the lesson where JavaScript meets real APIs. Every React data loader, every Next.js server component that reads a database, every Node script that calls a third-party service is written with async/await and usually fetch. Getting it slightly wrong makes pages slow (requests that run one by one) or flaky (no timeouts, no retries, errors swallowed), and interviewers know it.
async functions return promises
Put async before a function and two things change:
- It always returns a promise. A returned value becomes the fulfilled value; a thrown error becomes the rejection.
- Inside it you can use
await, which pauses the function until a promise settles, then gives you its value (or throws its error).
Press Run (⌘ Enter) to see what happens.await does not block the thread. It pauses only this function: the rest of the function is scheduled as a microtask for when the promise settles, and meanwhile the event loop keeps running other code. That is why async/await is "promises with nicer syntax", not a new mechanism.
What does this print?
async function run() {
console.log("2");
await null;
console.log("4");
}
console.log("1");
run();
console.log("3");Modern runtimes also allow top-level await in ES modules (and in this course's runner), which is why earlier lessons could write await sleep(100) outside any function. In a regular script or a CommonJS file, await only works inside an async function.
Errors with try/catch
With await, a rejected promise throws at that line, so normal try/catch/finally handles async errors exactly like synchronous ones:
Press Run (⌘ Enter) to see what happens.A frequent mistake is forgetting await. Without it, loadProfile(-1) returns a promise that rejects later, after the try block has already finished, so the catch never sees it and you get an unhandled rejection instead.
catch never run when save rejects?async function submit(form) {
try {
save(form);
} catch (e) {
showError(e);
}
}Sequential vs parallel
This is the most important performance habit in async code. Each await waits before moving on. If the next request does not need the previous one's result, waiting is wasted time.
Press Run (⌘ Enter) to see what happens.Sequential. await getUser() starts the first request and waits for it to finish before the next line runs.
The rule: start independent work first, await it together. Only go sequential when a step needs the previous result (you need the user's id to fetch their orders). If you do not want one failure to throw away the others, use Promise.allSettled instead of Promise.all.
for await
Some sources produce values over time: pages of an API, lines of a file, chunks of a stream. An async iterable delivers each value as a promise, and for await...of loops over it, awaiting each one in turn. An async function* (an async generator) is the simplest way to make one:
Press Run (⌘ Enter) to see what happens.Do not use for await (or await inside a regular loop) when the iterations are independent; that is the sequential trap again. Use Promise.all(items.map(...)).
The fetch API
fetch is the built-in HTTP client in browsers, Node 18+, Deno and Bun. Its shape:
const res = await fetch("https://api.example.com/users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Ada" }),
signal: AbortSignal.timeout(5000), // give up after 5 seconds
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const user = await res.json(); // reading the body is async toofetch returns a promise immediately. The request runs off the main thread.
Two things surprise everyone:
fetchdoes not reject on HTTP errors. A 404 or 500 is still a successful round trip, so the promise fulfils withres.ok === false. It only rejects on network failures (offline, DNS, CORS) or an abort. Always checkres.ok.- The body is read separately.
res.json(),res.text()andres.blob()each return a promise, and a body can be read only once.
The runnable blocks here cannot reach the network, so the examples use a fake fetch that returns the same shape: a promise of an object with ok, status and an async json().
Press Run (⌘ Enter) to see what happens.What does this print?
async function fakeFetch() {
return { ok: false, status: 500, json: async () => ({}) };
}
try {
const res = await fakeFetch("/api");
console.log("resolved", res.status);
} catch {
console.log("rejected");
}Timeouts and cancellation
A request with no timeout can hang for minutes. An AbortController lets you cancel: pass its signal to fetch, then call controller.abort() and the fetch rejects with an AbortError. For a plain timeout, AbortSignal.timeout(ms) creates a signal that aborts itself. Cancellation is also how React effects avoid setting state after a component unmounts.
Press Run (⌘ Enter) to see what happens.Retry with backoff
Networks fail transiently: a dropped connection, a 503 during a deploy, a 429 rate limit. A retry with exponential backoff waits a little longer after each failure (100 ms, 200 ms, 400 ms...) so a struggling server gets room to recover. Production code adds jitter (a random extra delay) so a thousand clients do not retry in lockstep.
Press Run (⌘ Enter) to see what happens.Note the return await fn() inside try: without await, a rejection would escape the try and skip the retry. Only retry operations that are safe to repeat (GET requests, or writes protected by an idempotency key), and never retry a 400 or 401, which will fail the same way every time.
Order the steps of a careful API call.
- Tap the steps below in the right order.
fetchJson with a timeout
Write an async function fetchJson(url, fetcher, timeoutMs = 1000). fetcher has the same shape as fetch (the tests pass a fake one): it is called as fetcher(url, { signal }) and resolves to a response with ok, status and an async json().
- Pass an
AbortController'ssignaltofetcher, and abort it if the request takes longer thantimeoutMs. - If
res.okis false, thrownew Error("HTTP " + res.status), e.g."HTTP 404". - Otherwise return the parsed body from
res.json(). - Clear the timer when you are done.
const user = await fetchJson("/api/users/1", fetch);retry with backoff
Write an async function retry(fn, times, delayMs = 0). It calls fn() (which may return a promise or throw) up to times attempts in total:
- As soon as an attempt succeeds, return its result.
- If an attempt fails and attempts remain, wait and try again. The wait doubles each time:
delayMs, then2 · delayMs, then4 · delayMs... - If every attempt fails, throw the last error.
let n = 0;
const flaky = async () => { n++; if (n < 3) throw new Error("503"); return "ok"; };
await retry(flaky, 5, 100); // "ok" after waiting 100 ms, then 200 ms- async function
- A function that always returns a promise and can use
awaitinside. - await
- Pauses the async function until a promise settles, then returns its value or throws its error. The thread keeps running other work.
- Promise.all for parallelism
- Start independent operations first, then await them together; total time is the slowest, not the sum.
- res.ok
- True when the HTTP status is 200 to 299.
fetchresolves on 404/500, so you must check it. - AbortController
- Creates a
signalyou pass tofetch; callingabort()cancels the request with an AbortError. - exponential backoff
- Retrying after waits that double each time (plus jitter) so a failing service can recover.