Lesson 70 of 296
async and await
What you will learn
- What
asyncandawaitdo - How they relate to promises
- Error handling with
try...catch - Running things in sequence and in parallel
awaitin loops- Top-level await
On this page
async functions
Putting async before a function makes it always return a promise.
async function getNumber() {
return 42;
}
getNumber().then((n) => console.log(n)); 42Returning a value fulfils the promise. Throwing an error rejects it.
await
Inside an async function, await pauses that function until a promise settles, then gives you its value.
async function showUser() {
const response = await fetch("/api/user/1");
const user = await response.json();
console.log(user.name);
}It reads like synchronous code, but it is not blocking: while showUser is paused, the rest of the program keeps running. Only this one function waits.
async/await is syntax built on promises. Everything you learned in Lesson 69 still applies.
Error handling
Use try...catch (Lesson 72):
async function loadUser(id) {
try {
const response = await fetch(`/api/users/${id}`);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return await response.json();
} catch (error) {
console.error("Could not load user:", error.message);
return null;
} finally {
hideSpinner();
}
}If an awaited promise rejects, await throws the error, and catch receives it.
Promise chain vs async/await
function loadOrders() {
return getUser(1)
.then((user) => getOrders(user.id))
.then((orders) => orders.length)
.catch(() => 0);
}
async function loadOrders() {
try {
const user = await getUser(1);
const orders = await getOrders(user.id);
return orders.length;
} catch {
return 0;
}
}Both do the same. async/await is usually easier to read, especially with conditions and loops.
Sequence vs parallel: the big performance mistake
async function loadDashboard() {
const user = await getUser(); takes 1 second
const posts = await getPosts(); takes 1 second
const stats = await getStats(); takes 1 second
}This takes 3 seconds, because each await waits before starting the next request. But these requests do not depend on each other.
Run them in parallel:
async function loadDashboard() {
const [user, posts, stats] = await Promise.all([
getUser(),
getPosts(),
getStats()
]);
}All three start at once. Total: about 1 second. Lesson 71 explains Promise.all.
Rule: use sequential await only when one step needs the result of the previous one.
await in loops
for...of waits for each item (sequential):
for (const id of ids) {
const user = await getUser(id);
console.log(user.name);
}Use this when order matters, or to avoid overloading a server.
forEach does NOT wait:
ids.forEach(async (id) => {
const user = await getUser(id);
});
console.log("done"); runs before any user has loadedforEach ignores the promises returned by the async callback. This is a common bug.
Parallel with map and Promise.all:
const users = await Promise.all(ids.map((id) => getUser(id)));For hundreds of items, running all at once can overload a server; limit how many run at the same time (Part 6, promise pool).
Forgetting await
async function save() {
const result = saveToDb(data); forgot await
console.log(result); Promise { <pending> }
}Without await, you get the promise, not the value. Errors from it are also not caught by your try...catch. TypeScript and ESLint rules (such as "no floating promises") help catch this.
Top-level await
In ES modules (Lesson 73), await can be used at the top level of a file, outside any function:
const config = await loadConfig();It does not work in old-style scripts or CommonJS files.
Common mistakes
- Using
awaitoutside anasyncfunction (a SyntaxError, except top-level await in modules). - Forgetting
await. - Awaiting independent requests one by one.
awaitinsideforEach.- No
try...catch, so rejections are unhandled.
How to say it in an interview
"async functions always return a promise, and await pauses only that function until a promise settles, without blocking the main thread; it is syntax over promises. I handle errors with try-catch, since a rejected await throws. The biggest mistake is awaiting independent operations sequentially; I start them together with Promise.all. for...of with await runs sequentially, while forEach does not wait for async callbacks at all. Top-level await works in ES modules."
Key words
| Word | Meaning |
|---|---|
| async function | A function that always returns a promise |
| await | Pauses an async function until a promise settles |
| Sequential | One after another |
| Parallel / concurrent | At the same time |
| Floating promise | A promise that is created but not awaited or handled |
| Top-level await | Using await outside a function, in modules |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.