Async
async / await
A way to write asynchronous code (requests, timers) as if it ran step by step, top to bottom.
Why it exists
A request to a server takes tens or hundreds of milliseconds. If the browser just waited during that time, the page would freeze: buttons wouldn't respond, animations would stop. So such operations are asynchronous: they return a promise — a "promise of a result" — and don't block the rest of the code. Results used to be handled in .then(...) chains, and code quickly turned into a staircase. async/await lets you write the same thing as an ordinary sequence of steps: "load the user, then their orders, then show them".
Where it's used
- Requests to a server:
const res = await fetch("/api/orders"). - Database work on the server:
await db.query(...). - Sequential steps: sign in → load the profile → load the settings.
- Timers and delays: show a notification, wait, hide it.
Syntax
async function name() {
const value = await promise;
}Examples
function wait(ms) {
return new Promise((resolve) => setTimeout(() => resolve(ms), ms));
}
async function demo() {
const ms = await wait(100);
return "Waited " + ms + " ms";
}
demo().then((text) => console.log(text)); // "Waited 100 ms"function loadUser(id) {
return Promise.resolve({ id, name: "Ann" });
}
async function greeting(id) {
const user = await loadUser(id);
return "Hi, " + user.name;
}
await greeting(1); // → "Hi, Ann"async function getFive() {
return 5;
}
getFive() instanceof Promise; // → true
await getFive(); // → 5async function always returns a promiseconst slow = (value, ms) => new Promise((r) => setTimeout(() => r(value), ms));
const [a, b] = await Promise.all([slow("tea", 30), slow("coffee", 30)]);
[a, b]; // → ["tea", "coffee"]Results after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
async before a function does two things: it lets you write await inside, and it makes the function always return a promise. Even return 5 inside it becomes a promise with the value 5.
await promise pauses this function until the promise settles. The rest of the program keeps running in the meantime — the interface doesn't freeze. When the promise is fulfilled, await returns its value; when it's rejected, await throws an error, just like throw.
That's why errors in asynchronous code are caught with an ordinary try...catch around the await.
Several awaits in a row run one after another. If the operations don't depend on each other, you can start them at once and wait for them together: await Promise.all([a(), b()]).
Traps
How it differs from…
try...catchawaitturns a rejected promise into an ordinary error, and try...catch catches it. That's why they're almost always used together.
When to pick something else
Don't make a function async if it does no asynchronous work — it will start returning a promise for no reason. And don't await in a loop when the operations are independent: start them all at once and wait with Promise.all.
Practice
Lessons where this appears
- The pizza is on its wayTale · Chapter 16 · Async
- Why doesn't setTimeout(…, 0) fire at once?Why? · Chapter 16 · Async
- The Endless SpinnerBoss · Chapter 16 · Async
- How a shop is builtTale · Chapter 17 · Project: an online shop
- ProductionBoss · Chapter 17 · Project: an online shop
- Mutant huntWorkshop · Chapter 27 · Testing