Skip to content

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.

16 min read0/5 questions

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:

  1. It always returns a promise. A returned value becomes the fulfilled value; a thrown error becomes the rejection.
  2. Inside it you can use await, which pauses the function until a promise settles, then gives you its value (or throws its error).
JavaScript
async function getNumber() { return 7; // wrapped: same as return Promise.resolve(7)} const result = getNumber();console.log(result instanceof Promise);console.log(await result); async function fail() { throw new Error("nope"); // becomes a rejected promise}await fail().catch((e) => console.log("caught:", e.message));
Output
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.

Predict the outputJavaScript

What does this print?

async function run() {
console.log("2");
await null;
console.log("4");
}
console.log("1");
run();
console.log("3");
Need a nudge? Hints walk you through it.

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:

JavaScript
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); async function loadProfile(id) { await sleep(10); if (id < 0) throw new Error(`no user ${id}`); return { id, name: "Priya" };} async function show(id) { let loading = true; try { const user = await loadProfile(id); console.log("hello", user.name); } catch (err) { console.log("error:", err.message); } finally { loading = false; console.log("loading:", loading); }} await show(1);await show(-1);
Output
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.

Quick check
Why does this catch never run when save rejects?
async function submit(form) {
try {
  save(form);
} catch (e) {
  showError(e);
}
}
Need a nudge? A hint rules out a wrong answer.

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.

JavaScript
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));// Three fake requests that each take 100 msconst getUser = () => sleep(100).then(() => ({ name: "Ada" }));const getOrders = () => sleep(100).then(() => [1, 2, 3]);const getPrefs = () => sleep(100).then(() => ({ theme: "dark" })); let t = Date.now();const user1 = await getUser();const orders1 = await getOrders();const prefs1 = await getPrefs();console.log(`sequential: ~${Math.round((Date.now() - t) / 100) * 100} ms`); t = Date.now();const [user2, orders2, prefs2] = await Promise.all([getUser(), getOrders(), getPrefs()]);console.log(`parallel: ~${Math.round((Date.now() - t) / 100) * 100} ms`);console.log(user2.name, orders2.length, prefs2.theme);
Output
Press Run (⌘ Enter) to see what happens.
Three 100 ms requests over time
0 ms100200300
getUser▮
getOrders
getPrefs

Sequential. await getUser() starts the first request and waits for it to finish before the next line runs.

1/4

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.

Quick check
Which version loads the user and the product catalogue in parallel?
Need a nudge? A hint rules out a wrong answer.

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:

JavaScript
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); async function* pages() { for (let page = 1; page <= 3; page++) { await sleep(20); // pretend to fetch the page yield [`item ${page}a`, `item ${page}b`]; }} for await (const items of pages()) { console.log(items.join(", "));}
Output
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:

fetch in a real app (not runnable here)
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 too
One fetch call
Your codefetchServerfetch(url, options)POST /users201 + headersResponseres.json()

fetch returns a promise immediately. The request runs off the main thread.

1/5

Two things surprise everyone:

  • fetch does not reject on HTTP errors. A 404 or 500 is still a successful round trip, so the promise fulfils with res.ok === false. It only rejects on network failures (offline, DNS, CORS) or an abort. Always check res.ok.
  • The body is read separately. res.json(), res.text() and res.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().

JavaScript
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));const db = { 1: { id: 1, name: "Ada" }, 2: { id: 2, name: "Sam" } }; async function fakeFetch(url) { await sleep(30); const id = Number(url.split("/").pop()); const user = db[id]; return { ok: Boolean(user), status: user ? 200 : 404, json: async () => (user ? user : { error: "not found" }), };} async function getUser(id) { const res = await fakeFetch(`/api/users/${id}`); if (!res.ok) throw new Error(`HTTP ${res.status}`); return res.json();} console.log((await getUser(1)).name);try { await getUser(99);} catch (e) { console.log("failed:", e.message);}
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputJavaScript

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

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.

JavaScript
function fakeFetch(url, { signal } = {}) { return new Promise((resolve, reject) => { const timer = setTimeout(() => resolve({ ok: true, status: 200, json: async () => ({ url }) }), 200); signal?.addEventListener("abort", () => { clearTimeout(timer); reject(new DOMException("The operation was aborted", "AbortError")); }); });} const controller = new AbortController();setTimeout(() => controller.abort(), 50); // give up after 50 ms try { await fakeFetch("/slow", { signal: controller.signal });} catch (e) { console.log(e.name);}
Output
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.

JavaScript
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); async function withRetry(fn, attempts = 3, baseMs = 50) { for (let i = 1; i <= attempts; i++) { try { return await fn(); } catch (err) { if (i === attempts) throw err; const wait = baseMs * 2 ** (i - 1); console.log(`attempt ${i} failed, retrying in ${wait} ms`); await sleep(wait); } }} let calls = 0;const flaky = async () => { calls++; if (calls < 3) throw new Error("503"); return "ok";}; console.log(await withRetry(flaky));
Output
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.

Put it in order5 steps

Order the steps of a careful API call.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
ChallengeMedium

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's signal to fetcher, and abort it if the request takes longer than timeoutMs.
  • If res.ok is false, throw new 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);
JavaScript
async function fetchJson(url, fetcher, timeoutMs = 1000) { // Create an AbortController, call fetcher(url, { signal }), check res.ok. return null;}
ChallengeMedium

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, then 2 · delayMs, then 4 · 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
JavaScript
async function retry(fn, times, delayMs = 0) { // Loop up to times; try/catch each attempt; wait between failures. return undefined;}
Key terms
async function
A function that always returns a promise and can use await inside.
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. fetch resolves on 404/500, so you must check it.
AbortController
Creates a signal you pass to fetch; calling abort() cancels the request with an AbortError.
exponential backoff
Retrying after waits that double each time (plus jitter) so a failing service can recover.