Module 4: Async / Await
async/await is syntax sugar over Promises β the same machinery underneath, but code that reads top-to-bottom like synchronous logic. This is how virtually all modern backend JavaScript is written.
4.1 The Two Rules
asyncmakes a function always return a Promise. Return a value β the promise fulfills with it. Throw β the promise rejects.awaitpauses the function (not the whole program!) until a Promise settles, then hands you the unwrapped value β or throws the rejection reason.
async function getAnswer() {
return 42; // caller receives Promise<42>
}
getAnswer().then(console.log); // 42
// The fetch chain from Module 3, rewritten:
async function getRepoCount(username) {
const userRes = await fetch(`https://api.github.com/users/${username}`);
const user = await userRes.json();
const reposRes = await fetch(user.repos_url);
const repos = await reposRes.json();
return repos.length;
}
// Top-level await works in ES modules (Node ESM + modern browsers):
const count = await getRepoCount("octocat");
At each await, the function suspends and JavaScript goes off to run other code (handle other requests, fire timers). When the promise settles, the function resumes where it left off. This is why one Node process can serve thousands of concurrent connections.
4.2 Error Handling with try / catch
async function getUser(id) {
try {
const res = await fetch(`/api/users/${id}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`); // remember: fetch
return await res.json(); // won't throw on 404
} catch (err) {
// Network failure, bad status, or invalid JSON all land here
console.error(`getUser(${id}) failed:`, err.message);
throw err; // re-throw, or return a fallback β decide DELIBERATELY
} finally {
// cleanup: close spinners, release locks, stop timers
}
}
Normally return await p and return p behave the same β but inside a try block they don't! return promise escapes before rejection is known, skipping your catch. return await promise keeps the error catchable locally. Inside try/catch, always return await.
4.3 Sequential vs Parallel β the #1 Performance Mistake
Every pair of awaits, ask: does B need A's result? If not, run them in parallel.
// β SLOW β sequential: second request waits for the first (~2s total)
const user = await fetchUser(); // 1s
const settings = await fetchSettings(); // 1s, but only starts after user!
// β
FAST β parallel: both start NOW (~1s total)
const [user2, settings2] = await Promise.all([
fetchUser(),
fetchSettings(),
]);
// β
Also fine β start both, await later:
const userP = fetchUser(); // fires immediately (no await)
const settingsP = fetchSettings(); // fires immediately
const u = await userP;
const s = await settingsP;
// Genuinely dependent work MUST be sequential β that's correct:
const profile = await fetchUser(id);
const posts = await fetchPosts(profile.postsUrl); // needs profile first
4.4 Loops and Async
const ids = [1, 2, 3, 4, 5];
// β BROKEN β forEach ignores returned promises; fires all at once,
// nothing waits, errors are unhandled:
ids.forEach(async id => await processOrder(id));
// β
Sequential β one at a time (rate-limited APIs, ordered writes):
for (const id of ids) {
await processOrder(id);
}
// β
Parallel β all at once, wait for all (independent work):
const results = await Promise.all(ids.map(id => processOrder(id)));
// β
Batched parallel β N at a time (be kind to APIs and DBs):
async function inBatches(items, size, worker) {
const out = [];
for (let i = 0; i < items.length; i += size) {
const batch = items.slice(i, i + size);
out.push(...await Promise.all(batch.map(worker)));
}
return out;
}
await inBatches(ids, 2, processOrder);
4.5 Real Backend Patterns
// Express route handler β the everyday shape:
app.get("/users/:id", async (req, res, next) => {
try {
const user = await db.users.findById(req.params.id);
if (!user) return res.status(404).json({ error: "Not found" });
res.json(user);
} catch (err) {
next(err); // hand to Express's error middleware β never
} // let a rejection escape a route handler!
});
// Concurrent independent queries per request:
app.get("/dashboard", async (req, res, next) => {
try {
const [stats, notices, activity] = await Promise.all([
db.getStats(req.userId),
db.getNotices(),
db.getRecentActivity(req.userId),
]);
res.json({ stats, notices, activity });
} catch (err) { next(err); }
});
// Graceful degradation β page must render even if a side-widget fails:
const [core, extras] = await Promise.allSettled([getCoreData(), getExtras()]);
if (core.status === "rejected") throw core.reason; // core is required
const extrasData = extras.status === "fulfilled" ? extras.value : null;
4.6 Async Iteration (a taste of advanced)
// for await...of β consume async streams one chunk at a time
import { createReadStream } from "node:fs";
import { createInterface } from "node:readline";
const lines = createInterface({ input: createReadStream("big.log") });
for await (const line of lines) {
if (line.includes("ERROR")) console.log(line);
}
// Async generators β produce values over time
async function* poll(url, ms) {
while (true) {
yield await fetch(url).then(r => r.json());
await new Promise(r => setTimeout(r, ms));
}
}
for await (const status of poll("/api/health", 5000)) {
console.log(status);
if (status.ok) break;
}
Common Beginner Mistakes
- Forgetting
awaitβ you getPromise {<pending>}instead of the value. If you see that in a log, you dropped an await. awaitinforEachβ silently does nothing useful. Usefor...oformap+Promise.all.- Accidental sequential execution of independent requests (see 4.3) β the most common real-world performance bug.
- Fire-and-forget without a catch:
doAsyncThing();with no await/catch means rejections vanish (and crash Node). If intentional, mark it:void doAsyncThing().catch(log); - Wrapping everything in try/catch reflexively and swallowing errors with empty catch blocks. Catch only where you can actually handle or add context.
- Making a function
asyncfor no reason β if there's no await inside, it just wraps the return value in a pointless promise.
Exercises
async function foo() {
console.log("1");
await null; // even awaiting a non-promise yields once!
console.log("2");
}
console.log("3");
foo();
console.log("4");
Solution
3, 1, 4, 2. Calling foo() runs synchronously until the first await (logging 1), then suspends. Sync code continues (4). The resumption is a microtask (2). Everything before the first await is synchronous β a subtle, frequently-tested fact.
Rewrite with async/await, preserving the fallback behavior:
function load() {
return fetchConfig()
.then(cfg => fetchData(cfg.url))
.catch(() => DEFAULT_DATA)
.then(data => render(data));
}
Solution
async function load() {
let data;
try {
const cfg = await fetchConfig();
data = await fetchData(cfg.url);
} catch {
data = DEFAULT_DATA;
}
return render(data); // runs with real OR default data, like the chain
}
Fetch 5 PokΓ©mon from https://pokeapi.co/api/v2/pokemon/{1..5} twice: once sequentially with for...of, once with Promise.all. Measure both with console.time. Try it in the playground.
Solution
const ids = [1, 2, 3, 4, 5];
const get = id => fetch(`https://pokeapi.co/api/v2/pokemon/${id}`).then(r => r.json());
console.time("sequential");
for (const id of ids) await get(id);
console.timeEnd("sequential"); // β sum of all latencies
console.time("parallel");
await Promise.all(ids.map(get));
console.timeEnd("parallel"); // β slowest single latency
Reimplement Module 3's retry using async/await, adding exponential backoff: wait 100ms, 200ms, 400ms⦠between attempts.
Solution
const wait = ms => new Promise(r => setTimeout(r, ms));
async function retry(fn, attempts, baseMs = 100) {
for (let i = 0; i < attempts; i++) {
try {
return await fn(); // return await β catchable here
} catch (err) {
if (i === attempts - 1) throw err; // last attempt β give up
await wait(baseMs * 2 ** i); // 100, 200, 400, ...
}
}
}
Notice how much clearer the loop is than the recursive promise version β this is the payoff of async/await.
Write mapLimit(items, limit, worker) β like Promise.all(items.map(worker)) but never more than limit workers in flight at once. Preserve result order. (This is the core of libraries like p-limit.)
Solution
async function mapLimit(items, limit, worker) {
const results = new Array(items.length);
let next = 0;
async function runner() {
while (next < items.length) {
const i = next++; // claim an index atomically
results[i] = await worker(items[i], i);
}
}
// Start `limit` runners; each pulls the next item when free
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, runner));
return results;
}
// 100 URLs, at most 5 concurrent requests:
const pages = await mapLimit(urls, 5, url => fetch(url).then(r => r.text()));
Single-threadedness makes next++ safe β no locks needed. Understanding why is a great interview discussion.
Build a page (or CLI) that takes a GitHub username, fetches the user then their repos (dependent requests), fetches languages for the top 5 repos in parallel with a concurrency limit, handles 404/rate-limit errors gracefully, and renders a summary. Full spec on the Projects page.
Interview Questions from This Module
What does the async keyword actually do?
It makes the function return a Promise (wrapping returned values, converting throws into rejections) and enables await inside. It does NOT make the function run on another thread or make it non-blocking by itself.
Is await blocking?
It suspends only the containing async function; the event loop keeps running other code. Contrast with truly blocking calls (e.g. fs.readFileSync) which freeze the whole thread β a serious sin in a Node server.
How do you run async operations in parallel? Sequentially?
Parallel: start all promises first, then await Promise.all([...]) (or map + all). Sequential: for...of with await inside. Bounded parallelism: a concurrency limiter like p-limit or batching.
What happens to an error thrown inside an async function nobody awaits?
The returned promise rejects with it. With no .catch/await, it becomes an unhandled rejection β Node (v15+) crashes the process by default. Always await or attach a catch, even for fire-and-forget tasks.