async/await in Depth
Writing asynchronous code that reads top-to-bottom with async functions and the await keyword.
What you'll learn
- Declaring async functions and what they return
- Awaiting promises and pausing execution
- Error handling with try/catch around await
- Running promises in parallel with Promise.all
- Top-level await and the no-await-in-loop trade-off
Concept
Linear Async Code
async/await (ES2017) is syntax built on top of promises. An async function always returns a promise — if you return a value, it is wrapped in a promise; if you return a promise, it is passed through. Inside an async function, await pauses execution until a promise settles, then yields its value. The result is asynchronous code that reads like synchronous code, top to bottom.
Error Handling
Because await throws when a promise rejects, you wrap await calls in try/catch — the same construct used for synchronous errors. This is a major readability win over .catch() chains, especially when multiple async steps can fail in different ways. A single try/catch can guard an entire sequence.
Sequential vs Parallel
A common mistake is awaiting independent calls one after another, which runs them sequentially and wastes time. If the calls do not depend on each other, start them all at once and await the combined result with Promise.all. This turns N sequential round-trips into one parallel batch.
Awaiting in Loops
Using await inside a for loop runs each iteration sequentially. This is correct when each iteration depends on the previous one, but slow for independent work. For independent items, use Promise.all(items.map(asyncFn)) to run them concurrently. Reserve sequential await-in-loop for genuinely dependent steps.
Top-Level Await
In ES modules (not CommonJS), you can use await at the top level of a module without wrapping it in an async function. This simplifies module initialization that needs async setup. In non-module scripts and CommonJS, you still need an async wrapper or an IIFE.
Under the Hood
async/await does not replace promises — it desugars to promise chains. Every async function is a function returning a promise, and every await is a then call. Understanding promises is therefore essential to debug async/await code, especially around error handling and parallelism.
Example
// An async function always returns a promise
async function fetchUser(id) {
const res = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
// try/catch for error handling — reads like sync code
async function getUserSafe(id) {
try {
const user = await fetchUser(id);
return user;
} catch (e) {
console.error("Failed:", e.message);
return null;
}
}
// Sequential — each waits for the previous (slow!)
async function loadSequential() {
const a = await fetchUser(1);
const b = await fetchUser(2);
return [a, b];
}
// Parallel — both start at once (fast!)
async function loadParallel() {
const [a, b] = await Promise.all([fetchUser(1), fetchUser(2)]);
return [a, b];
}
// Sequential await in a loop — correct for dependent steps
async function fetchChain(startId, steps) {
let current = startId;
for (let i = 0; i < steps; i++) {
const user = await fetchUser(current);
console.log("step", i, user?.name);
current = user?.id + 1; // next depends on previous
}
}
// Top-level await in an ES module
const users = await loadParallel();
console.log("loaded:", users.length);
Shows an async fetch with error handling, sequential vs parallel loading (Promise.all), sequential await in a loop for dependent steps, and top-level await in a module.
Try it
- HTTP Request Tester
Send requests and practice async/await patterns with real responses.
- WebSocket Client Tester
Async messaging patterns that benefit from async/await.
Common mistakes
The mistake
Awaiting independent calls sequentially instead of in parallel
The fix
If calls do not depend on each other, use Promise.all([fetchA(), fetchB()]) to run them concurrently. Sequential await wastes time waiting for each one before starting the next.
The mistake
Forgetting that async functions return a promise, not the value directly
The fix
An async function always returns a promise. To get the value, the caller must await it or use .then(). You cannot return a plain value from an async function to a synchronous caller.
Related Resources
Related Cheatsheets
- JavaScript Cheatsheet
async/await syntax, error handling, and parallel patterns.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.