Async/Await
`async`/`await` as sugar over promises that reads top to bottom, and the mistake of awaiting serially in a loop when the work could run concurrently.
Async/Await
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- `async`/`await` is syntax sugar over promises, not a different async mechanism — an `async` function always returns a promise, and `await` just pauses that function until the promise it's given settles.
- `await expression` unwraps a fulfilled promise into its plain value, directly in the line of code that awaited it, which is what lets async logic read top to bottom instead of nesting inside `.then()` callbacks.
- If the awaited promise rejects, `await` throws that rejection as a regular exception at the `await` line — which is exactly what makes ordinary `try`/`catch` work around async code, covered in the next lesson.
- Writing several independent `await`s one after another inside a loop runs them *serially* — each one waits for the last to finish before even starting the next — even when none of them actually depends on the others' results.
- The fix is to start all the promises first (so the underlying work begins concurrently), and only then await them together, usually with `Promise.all` — turning "wait, then start the next" into "start everything, then wait once".
Sugar, not a new mechanism
Everything in promises — states,
.then(), the combinators — is still exactly what’s running underneath
async/await. Nothing new is added to the language’s actual async
model here; async/await just changes how you write code against
promises, so it reads like ordinary, sequential, top-to-bottom code
instead of a chain of callbacks.
An async function always returns a promise, even if you never see
yourself constructing one:
async function getUser() {
return { name: "Ada" };
}
getUser(); // Promise, fulfilled with { name: "Ada" } — not the object directly
And inside an async function, await pauses execution at that line
until the promise it’s given settles, then resumes with the result:
async function getUserOrders(userId) {
const user = await fetchUser(userId); // pause here until this resolves
const orders = await fetchOrders(user.id); // then pause here
return orders;
}
Compare that to the equivalent .then() chain from the previous lesson —
same operations, same order, but no nested callbacks and no .then() to
thread values through. If the awaited promise rejects instead of
fulfilling, await throws that rejection right at the await line, as a
normal exception — which is the hook the next lesson
uses to wrap async code in ordinary try/catch.
The mistake almost everyone makes once: awaiting serially in a loop
await pauses the function it’s written in — not the operation it’s
awaiting. That distinction is easy to lose track of inside a loop:
// Each iteration waits for the previous one to fully finish first
for (const id of userIds) {
const user = await fetchUser(id); // nothing starts for id #2 until #1 is done
results.push(user);
}
If fetchUser takes 200ms and there are ten ids, this takes roughly two
full seconds — even though none of these fetches actually depends on any
other one finishing first. Writing await inside the loop body means the
next iteration’s call doesn’t even begin until the current await
resolves, so independent work gets serialized for no reason.
The fix separates “start the work” from “wait for the work”:
// Every fetchUser call starts immediately, all at once
const promises = userIds.map((id) => fetchUser(id));
// Now wait for all of them together
const results = await Promise.all(promises);
userIds.map(...) calls fetchUser for every id without ever awaiting
inside the loop, so all ten requests begin concurrently on the first
line. The single await Promise.all(promises) then waits for all of them
together. Same ten requests, same results — but now bounded by the
slowest one, not the sum of all of them. This is the single most common
performance bug in async/await code, and it’s worth checking for
deliberately any time you see await written inside a for/for...of
loop.
Where this fits
This lesson assumes promises directly —
await only makes sense once you know what a promise’s states and
settling actually mean. It also leans on iterators and generators:
the pause-and-resume behavior that lets an async function suspend at an
await and later continue with the resolved value is the same mechanism
generators use to suspend at a yield, just pre-wired specifically for
promises. From here, error handling and custom errors
is the natural next step — now that a rejected await throws like any
other exception, try/catch becomes the normal way to handle it.
Check yourself
Is `async`/`await` a different way of doing asynchronous work than promises, or something built on top of promises?
It's built directly on top of promises — not a separate mechanism. An `async` function always returns a promise under the hood, and `await` is just a way of pausing that function until a promise settles, instead of attaching a `.then()` callback to it by hand. Everything from the previous lesson — states, chaining, rejection — is still happening; `async`/`await` just changes how it reads.
What does `await somePromise` actually evaluate to once that promise fulfills, and what happens at that line if it rejects instead?
If the promise fulfills, `await` evaluates to the promise's fulfilled value directly — no `.then()` callback needed, you can just assign it to a variable on the next line. If the promise rejects, `await` throws that rejection as a regular exception right at the `await` expression, which is why `try`/`catch` is the natural way to handle a failed `await`.
What's wrong with this code if `processItem` doesn't depend on any other item's result: `for (const item of items) { await processItem(item); }`?
It processes every item one at a time, strictly in order — the loop doesn't even start item 2 until item 1's `await` has fully resolved, even though nothing here actually requires that ordering. If each item's work takes, say, 200ms and there are ten of them, this takes roughly 2 seconds total when it could have taken roughly 200ms if they ran at the same time.
How do you fix the loop above so the items are processed concurrently instead of one at a time?
Start every promise first, without awaiting inside the loop, then await them together: `const results = await Promise.all(items.map((item) => processItem(item)));`. Calling `processItem` for every item right away kicks off all the underlying work concurrently; the single `await Promise.all(...)` at the end just waits for all of it to finish, instead of serializing it.
Why is it often said that async/await is "generators and promises wired together" under the hood?
A generator can pause mid-execution at a `yield` and later resume exactly where it left off, with its local variables intact — that's the same pause-and-resume shape `await` needs to suspend an `async` function until a promise settles and then continue from that exact point. `async`/`await` is effectively that generator pause/resume machinery, pre-wired specifically to pause on a promise and resume with its resolved value.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.