T5 Modern JavaScript (ES6 and later) · Lesson 8
async and await
Writing promises so that they read from top to bottom: async functions, which always give a promise; await, which pauses one function while everything else carries on; try and catch around awaited steps; choosing between one at a time and all together; top-level await in modules; and walking values that arrive slowly with for await...of.
- write async functions, and say what they return when they return a value or throw
- use await, and say what it pauses and what it does not
- handle failures with try, catch and finally around awaited steps
- choose between awaiting one at a time and starting everything together with Promise.all
- use await at the top level of a module, and say where it is not allowed
- walk values that arrive slowly with for await...of and async generators
The back cover
Chains of then work, but a long chain reads sideways, step after step inside little functions. The words async and await let the same promises be written from top to bottom, like ordinary code. The program still never stops to wait.
These pages show async functions, which always give a promise, and await, which pauses one function while everything else carries on. They show try and catch around awaited steps, and when to await one at a time or together. They show await at the top of a module, and async generators for values that arrive slowly.
Before you start
The story: A ledger of slips
The courier's promises have saved the upper floor, and now they are everywhere. To fit one spring, the script sends for the part, then the grease, then the key, and every step hangs from the one before on a long then. Working out what any line does means reading the whole chain, and three of the clockmakers have given up trying.
Yesterday one of them wrote a step that forgot its return, and a clock was wound with nothing at all.
Master Hakim Verge reads the chain with a finger, and loses his place twice. "The promises are sound," he says. "The writing is not. A clockmaker's instructions read from top to bottom: do this, wait, do that. Make the Script read the same."
Promises solved the staircase of callbacks, and a long chain of then is still harder to read than plain steps. The words async and await let promise code read from top to bottom, like the code you have written all along. Nothing changes underneath: they are promises, written another way.
It builds on these ideas. Each one has a tiny example, so you can check that you remember it.
| What you already know | A tiny example | Where it comes back |
|---|---|---|
| Promises and their states. | pending, fulfilled, rejected | An async function gives one. |
| then chains. | wait(50).then(next) | Rewritten as plain lines. |
| The wait helper. | wait(ms, value) | A stand-in for a slow server. |
| catch and finally. | .catch((err) => ...) | try, catch and finally around await. |
| try and catch. | try { ... } catch (err) { ... } | They now work on promises. |
| Promise.all. | Promise.all([a, b]) | Doing things together. |
| The event loop. | Running code, microtasks, tasks. | What runs while a function is paused. |
| Modules. | <script type="module"> | await at the top level. |
| Generators and for...of. | function* and yield | Values that arrive slowly. |
| Destructuring. | const [a, b] = list; | Unpacking Promise.all's values. |
By the end of this lesson you will be able to:
- write async functions, and say what they return when they return a value or throw;
- use await, and say what it pauses and what it does not;
- handle failures with try, catch and finally around awaited steps;
- choose between awaiting one at a time and starting everything together with Promise.all;
- use await at the top level of a module, and say where it is not allowed;
- walk values that arrive slowly with for await...of and async generators.
How to follow this lesson
The blocks on this page use the wait helper of the promises lesson as a stand-in for a slow server, and the Run button waits for each block's timers, up to 3 seconds. The next lesson swaps wait for a real request, with no other change to the code around it.
In one line
async and await are promises written from top to bottom; this lesson shows what they pause, how they fail, and when to do things together.
Async functions
At a glance
A courier's receipt is handed over at once, even though the parcel arrives later. An async function works like that receipt: whatever it does, it hands back a promise straight away.
Writing async in front of a function makes it always give a promise. A value it returns fulfils that promise, and an error it throws rejects it. Declarations, arrow functions and methods can all be async, so any kind of function can use await inside it. Even return 5 gives back a promise of 5.
Take a guess: Which language had async and await first, years before JavaScript?
Put the word async in front of a function, and it changes in one way: it always gives back a promise. Whatever the body returns becomes the promise's value.
A function written with async in front. Calling it gives a promise at once. When the body returns a value, the promise is fulfilled with that value; when the body throws, the promise is rejected with what was thrown.
async function f() {
return 5;
}
const p = f();
console.log(p instanceof Promise);
p.then((v) => console.log(v));
true
5
The body says return 5, and the caller receives a promise of 5, heard with then. A throw inside the body does not reach the caller as an exception. It becomes a rejection, heard with catch:
async function f() {
throw new RangeError("too many");
}
f().catch((e) => console.log(e.name, e.message));
RangeError too many
Declarations, arrows and methods can all be async. Getters, setters and constructors cannot, as they must give their answer at once.
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
class Clock {
async chime() {
await wait(10);
return "dong";
}
}
const double = async (x) => x * 2;
new Clock().chime().then((v) => console.log(v));
double(21).then((v) => console.log(v));
42
dong
double finished first, as it had nothing to wait for; chime had a wait of 10 milliseconds. The word await in chime is the next section's subject.
| The body does this | The promise it gave back |
|---|---|
| returns a value | is fulfilled with that value |
| returns nothing | is fulfilled with undefined |
| returns a promise | follows that promise |
| throws | is rejected with what was thrown |
Worked example 1
A cab app's fare will soon come from a server, so getFare(km) must give a promise, even now, when it only multiplies. Write it as an async function at ₹15 a kilometre, rejecting a distance of 0 or less, and use it twice.
What we have: a distance, and a rule for bad distances
What we need: a promise of the fare, or a rejection
The plan: mark the function async, throw a RangeError for a bad distance, and return the fare; callers use then and catch
async function getFare(km) {
if (km <= 0) throw new RangeError(`Bad distance: ${km}`);
return km * 15;
}
getFare(10).then((fare) => console.log(`₹${fare}`));
getFare(-2).catch((err) => console.log(err.message));
₹150
Bad distance: -2
10 km gives ₹150, and −2 km is rejected.
Check: the throw did not stop the program: it became a rejection, heard by catch.
A path that fails: wrapping the call in try and catch without await: try { getFare(-2); } catch (e) { ... }. The call returned a promise, so nothing was thrown there, and the rejection goes unhandled.
When you are stuck: an async function gives something strange
It always gives a promise: read its value with then, or with await in the next section.
A throw inside it does not reach a plain try around the call: it becomes a rejection.
If then receives undefined, the body did not return.
Remember that async goes in front of function, or in front of an arrow's brackets.
Your turn
async function name() {
return "Asha";
}
console.log(typeof name());
name().then((n) => console.log(n));
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
object
Asha
- A promise is an object.
- then hears the value that was returned.
It prints object, then Asha.
What does an async function that has no return give?Tap to reveal
- It still gives a promise.
- With no value, the promise is fulfilled with undefined.
A promise of undefined.
How do you write an async arrow that takes x and returns x + 1?Tap to reveal
- async goes in front of the brackets.
const next = async (x) => x + 1;
Did you know?
Older in C#
async and await were not invented for JavaScript. Microsoft's history of C# says that version 5.0, released in August 2012, put nearly all of its effort into the async and await model for asynchronous programming. Wikipedia adds that F# had asynchronous workflows with await points in 2007, and that Python and TypeScript took up async and await in 2015, before JavaScript did.
Why it fits here: It answers this topic's question: the async and await keywords reached JavaScript after C#, F#, Python and TypeScript had them.
Sources: Microsoft Learn: The history of C#; Wikipedia: Async/await
async functions, 2017
JavaScript's async functions arrived in the 2017 edition of the standard, whose section 14.6 is called Async Function Definitions. TC39's list of finished proposals names Async functions, by Brian Terlson. Before them, code wrote chains of then. An async function keeps the promise underneath: it always gives one back, whatever its body returns.
Why it fits here: It dates this topic's async functions: they joined the standard in 2017, two years after promises.
Sources: ECMAScript 2017 Language Specification; TC39: Finished Proposals
In one line
async in front of a function makes it always give a promise: a returned value fulfils the promise, and a throw rejects it. Declarations, arrows and methods can all be async.
await: pause here, and carry on after
At a glance
A cook waiting for rice to boil does not freeze the whole kitchen; the other cooks carry on. Only the one dish waits for its pot.
await pauses the async function it is in until a promise settles, and gives back its value. It never pauses the program: the caller and the page carry on, and the function continues from where it stopped when the value is ready. Even await on a value that is not a promise waits for one turn.
Take a guess: Does await 5, on a plain number, carry on at once?
Inside an async function, the word await in front of a promise pauses the function until the promise settles, and then gives the promise's value, as if the value had been there all along.
An operator used inside an async function. await p pauses that function until p settles. If p is fulfilled, the expression gives its value; if p is rejected, the expression throws its reason.
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
async function brew() {
console.log("water on");
const tea = await wait(50, "tea");
console.log(tea, "ready");
return tea;
}
brew().then((t) => console.log("serving", t));
console.log("meanwhile");
water on
meanwhile
tea ready
serving tea
Follow the order. brew starts and prints water on. At await, it pauses, and the call gives back its promise to the caller. So the last line runs: meanwhile. Fifty milliseconds later, wait is fulfilled, brew carries on from where it stopped, and tea holds the text tea. When brew returns, the then runs.
This is the most important fact about await: it pauses one function, not the program. The page stays free. Clicks, timers and other functions all go on while brew is paused, which is what the upper floor's clocks needed.
Paused functions take turns
Even await null, with nothing to wait for, gives way to the code that is running, because what comes after an await always runs later:
async function f() {
console.log("a");
await null;
console.log("c");
}
f();
console.log("b");
a
b
c
Two async functions called one after the other run side by side, each paused at its own await:
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
async function first() {
console.log("1");
await wait(40);
console.log("3");
}
async function second() {
console.log("2");
await wait(10);
console.log("4");
}
first();
second();
1
2
4
3
first printed 1 and paused; second printed 2 and paused. second's wait was shorter, so its 4 came before first's 3. The event loop of the promises lesson is doing all of this: what follows an await is a callback, in new clothes.
The same chain, top to bottom
Here is the booking of the promises lesson, rewritten. Each then has become one line with await:
| With then | With await |
|---|---|
wait(40, "seat").then((seat) => ...) | const seat = await wait(40, "seat"); |
| a step returns the next promise | the next line awaits it |
| each step's value is gone by the next step | every const stays in reach |
.catch((err) => ...) at the end | try { ... } catch (err) { ... } around the lines |
Worked example 2
Rewrite a ticket booking of three slow steps as one async function: check the seat, take the payment, send the ticket. The ticket must name the seat and the payment, so later steps need earlier values.
What we have: three steps in order, and values that later steps need
What we need: one function that reads top to bottom
The plan: await each step on its own line, keeping each value in a const, and build the ticket from them
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
async function book() {
const seat = await wait(30, "seat 42");
console.log("got", seat);
const payment = await wait(30, "₹350");
console.log("took", payment);
const ticket = await wait(30, `${seat}, paid ${payment}`);
return ticket;
}
book().then((t) => console.log("ticket:", t));
got seat 42
took ₹350
ticket: seat 42, paid ₹350
The ticket reads seat 42, paid ₹350.
Check: the last step used seat and payment from the steps above it, which a then chain would have had to pass along by hand.
A path that fails: a then chain whose last step needs seat. The name seat was a parameter of the first step's arrow, so it is out of reach there. The usual repair, a let outside the chain, is exactly what await makes needless.
When you are stuck: await does not seem to work
SyntaxError: await is only valid in async functions: mark the function async.
A value that is a promise means the await is missing.
Only the async function pauses: lines after the call still run at once.
Print before and after each await, and read the order.
Your turn
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
async function go() {
console.log("A");
const v = await wait(10, "C");
console.log(v);
}
go();
console.log("B");
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
A
B
C
- go prints A and pauses at await.
- The last line prints B.
- After 10 ms, go prints C.
It prints A, B, C.
What does await pause?Tap to reveal
- One function, not the program.
Only the async function it is in; everything else carries on.
What does await 5 give?Tap to reveal
const v = await 5;
console.log(v);
5
The value 5: a plain value needs no waiting, though what follows still runs later.
Did you know?
Even await 5 waits
await always takes a turn. MDN explains that when the awaited value is ready, another microtask is scheduled to continue the paused code, even if the value is an already-resolved promise or not a promise at all. The standard's steps show why: await first turns any value into a promise, with PromiseResolve. So code after await 5 runs only after other queued microtasks.
Why it fits here: It answers this topic's question: await on a plain value still pauses for one turn, so the code after it runs later.
Sources: MDN: await; ECMAScript Language Specification: Await
A bug that made await faster
await got faster thanks to a bug. V8's team writes that Node.js 8 had a bug that caused await to skip microticks in some cases, which made programs faster. The bug started as an unintended break from the standard, but it later gave the team the idea for an optimization, and V8 went on to remove two extra microticks from every await.
Why it fits here: It shows that this topic's await has a cost in microtasks, and that engine makers worked to make it smaller.
In one line
await pauses the async function it is in until a promise settles, and gives its value. It never pauses the program: the caller and the page carry on, and the function continues from where it stopped.
Failures with try and catch
At a glance
A safety net under a whole trapeze act catches a fall from any of its moves. One try around several awaited steps catches a failure in any of them.
At await, a rejected promise throws, so try, catch and finally work as they do for ordinary code. Inside a try, write return await, so a failure is caught there. Without the await, the promise leaves the try before it fails. Every async call needs someone listening for its failure, or the failure becomes an unhandled rejection.
Take a guess: Why did a popular linter retire its rule against return await?
When an awaited promise is rejected, the await line throws, like any line that throws. So the try and catch of the errors lesson work on promises, with no new syntax:
const fail = () => Promise.reject(new Error("no milk"));
async function make() {
try {
await fail();
console.log("never");
} catch (err) {
console.log("caught:", err.message);
} finally {
console.log("cleaned up");
}
}
make();
caught: no milk
cleaned up
The line after the await was skipped, the catch received the reason, and finally ran last. It reads exactly like the errors lesson, and one try can cover many awaited steps, as one catch covers a whole chain.
A failure nobody catches
An async function that throws, with no catch inside it or around its call, gives a rejected promise that nobody hears. It is an unhandled rejection, reported with the function in its trace:
async function f() {
throw new Error("x");
}
f();
Uncaught Error: x
at f (line 2)
at line 4
So every call to an async function needs someone listening: an await inside a try, a catch on the call, or a caller that does one of these.
Trying again
Because await works inside loops, a job that sometimes fails can be tried again with a plain for loop. The function returns at the first success, and throws again when the tries run out:
async function retry(job, times) {
for (let i = 1; i <= times; i++) {
try {
return await job();
} catch (err) {
console.log(`try ${i} failed: ${err.message}`);
if (i === times) throw err;
}
}
}
let calls = 0;
const flaky = async () => {
calls++;
if (calls < 3) throw new Error("busy");
return "served";
};
retry(flaky, 5).then((v) => console.log(v));
try 1 failed: busy
try 2 failed: busy
served
return await, inside a try
One small trap sits in that code, and the word await avoids it. A return without await hands the promise to the caller, and the function is over, so a try around it never sees the failure:
async function f() {
try {
return Promise.reject(new Error("x"));
} catch (e) {
return "caught";
}
}
f().catch((e) => console.log("outside", e.message));
outside x
async function f() {
try {
return await Promise.reject(new Error("x"));
} catch (e) {
return "caught";
}
}
f().then((v) => console.log(v));
caught
| Written | What happens to a failure |
|---|---|
await p inside try | it throws there, and catch hears it |
return p inside try | the promise leaves the function; catch never hears it |
return await p inside try | it throws there, and catch hears it |
p with no await or catch | an unhandled rejection |
Worked example 3
A school's results page loads the marks with a loading sign showing. It must always hide the sign, show the marks when they come, and show one message when they fail. Write it with try, catch and finally.
What we have: a load that may fail, and a sign to hide either way
What we need: the marks or a message, with the sign hidden in both cases
The plan: show the sign, await the load in try, show the message in catch, and hide the sign in finally
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
async function load(roll) {
await wait(20);
if (roll === 0) throw new RangeError("no such roll number");
return 412;
}
async function show(roll) {
console.log("sign on");
try {
const marks = await load(roll);
console.log(`${marks} marks`);
} catch (err) {
console.log(`Could not load: ${err.message}`);
} finally {
console.log("sign off");
}
}
await show(17);
await show(0);
sign on
412 marks
sign off
sign on
Could not load: no such roll number
sign off
Roll 17 shows 412 marks; roll 0 shows the message; the sign goes off both times.
Check: finally ran after the marks, and after the failure.
A path that fails: hiding the sign on the line after the await, inside try. A failure skips that line, and the spinner never stops.
When you are stuck: a failure is not caught
Is the failing call awaited inside the try? Without await, the failure leaves the try.
Inside a try, write return await, not return.
Uncaught Error with an async function in its trace means nobody listened: add a catch at the top.
A catch that cannot handle a failure should throw it again.
Your turn
async function f() {
try {
await Promise.reject(new Error("a"));
console.log("b");
} catch (e) {
console.log(e.message);
}
console.log("c");
}
f();
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
a
c
- The await throws, so b is skipped.
- The catch prints a.
- The function goes on after the try: c.
It prints a, then c.
What does a rejected promise do at an await?Tap to reveal
- The await expression throws the reason.
It throws, at that line.
Why write return await job(); inside a try, and not return job();?Tap to reveal
- Without await, the promise leaves the function unsettled.
- The try has ended by the time it fails.
So that the catch can hear a failure.
Did you know?
A lint rule that changed its mind
ESLint once had a rule against return await, and then retired it. The rule was deprecated in ESLint v8.46.0, with no replacement. Its page now explains why: return await on a promise no longer causes an extra microtask, and it gives a better stack trace for debugging. The old advice came from the early days of promises, when the extra step did cost time.
Why it fits here: It answers this topic's question, and backs its advice to write return await inside a try: the cost is gone, and the error trace is better.
Source: ESLint: no-return-await
Traces across await
An error thrown after several awaits can still show how it got there. V8's team writes that Chrome DevTools supports async stack traces, which include the asynchronous part of the stack as well as the current one. Logs on a server see only Error#stack, so V8 built zero-cost async stack traces, which add the async function calls to it, through await and Promise.all.
Why it fits here: It helps with this topic's failures: the trace of an error can list the async calls that led to it, not only the last step.
In one line
At await, a rejected promise throws, so try, catch and finally work as usual, around many steps at once. Inside a try, write return await. Every async call needs someone listening, or its failure becomes an unhandled rejection.
One at a time, or together
At a glance
Two errands in different shops are faster done by two people at once than by one person in turn. Code that waits for two servers can do the same.
Use await in order when a step needs the one before it. Start independent jobs together, and then await Promise.all, which takes as long as the slowest job, not the sum of them all. And note that forEach does not wait for async functions; use for...of with await, or map with Promise.all.
Take a guess: Will a browser really send a hundred requests to one server all at once?
await makes one slow habit very easy: waiting for things one at a time when they could all run together. Each await holds up the lines below it, and that is sometimes what you want, and sometimes a waste.
One at a time
In a for...of loop, each await finishes before the next turn starts. The jobs run strictly in order, whatever their times:
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
const order = [];
for (const n of [30, 10, 20]) {
await wait(n);
order.push(n);
}
console.log(order);
[ 30, 10, 20 ]
This is right when each step needs the one before it, or when a server must not be asked many things at once.
Together
When the jobs do not depend on each other, start them all first, and then wait for all of them. map starts one job for each item and gives an array of promises, and Promise.all waits for the array:
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
const order = [];
await Promise.all([30, 10, 20].map(async (n) => {
await wait(n);
order.push(n);
}));
console.log(order);
[ 10, 20, 30 ]
Now the jobs finished in the order of their times. And when each job gives a value, Promise.all still gives the values in the order of the inputs, however the jobs finished:
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
const values = await Promise.all([30, 10, 20].map((n) => wait(n, n * 2)));
console.log(values);
[ 60, 20, 40 ]
Here is the difference, read off the clock. Two waits of 200 milliseconds, one after the other, then together:
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
let start = Date.now();
await wait(200);
await wait(200);
const oneByOne = Date.now() - start;
start = Date.now();
await Promise.all([wait(200), wait(200)]);
const together = Date.now() - start;
console.log(oneByOne >= 390, together < 390);
true true
One by one took about 400 milliseconds, together about 200. On a page that loads ten such things, that is the difference between two seconds and a fifth of a second.
| Ask | If yes | Write |
|---|---|---|
| does this step need the last step's result? | one at a time | await on each line, or in for...of |
| must the steps never overlap? | one at a time | await in for...of |
| are the jobs independent? | together | await Promise.all(list.map(job)) |
| should one failure not stop the others? | together, with a report | await Promise.allSettled(...) |
forEach does not wait
forEach calls its function for each item and ignores what it returns. An async function returns a promise, so nobody waits for it, and the line after the forEach runs at once:
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
const results = [];
[1, 2].forEach(async (n) => {
await wait(10);
results.push(n);
});
console.log(results.length);
0
Use for...of to go one at a time, or map with Promise.all to go together.
Worked example 4
A student's page needs the student first, as the marks and the attendance are looked up by the student's id. Those two do not depend on each other. Load them as fast as the order allows.
What we have: one step that the others need, and two independent steps
What we need: all three pieces, with the two independent ones at the same time
The plan: await the student on its own line, then await Promise.all for the other two, unpacking the values
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
const getStudent = () => wait(30, { id: 7, name: "Asha" });
const getMarks = (id) => wait(40, `${id}: 412 marks`);
const getDays = (id) => wait(20, `${id}: 186 days`);
const student = await getStudent();
const [marks, days] = await Promise.all([getMarks(student.id), getDays(student.id)]);
console.log(student.name, "|", marks, "|", days);
Asha | 7: 412 marks | 7: 186 days
It shows Asha | 7: 412 marks | 7: 186 days.
Check: the two lookups used the id, so they had to come after the student, and they ran side by side.
A path that fails: three awaits in a row. It works, and takes 90 milliseconds where 70 would do; on a real page with ten lookups the wait adds up.
When you are stuck: async work runs too slowly, or in the wrong order
Too slow? Look for await in a loop on jobs that could run together.
Results in the wrong order? Promise.all keeps the input order in its values, but side effects happen as jobs finish.
A line after a forEach runs too early? forEach does not wait: use for...of, or map with Promise.all.
One failure loses everything? Use allSettled.
Your turn
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
const seen = [];
for (const n of [20, 5]) {
await wait(n);
seen.push(n);
}
await Promise.all([20, 5].map(async (n) => {
await wait(n);
seen.push(n * 10);
}));
console.log(seen);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
[ 20, 5, 50, 200 ]
- The loop goes in order: 20, then 5.
- Together, the 5 ms job finishes first: 50, then 200.
It prints [ 20, 5, 50, 200 ].
How long do await wait(300); await wait(100); take, and how long does await Promise.all([wait(300), wait(100)]) take?Tap to reveal
- One by one, the times add.
- Together, the slowest decides.
About 400 ms and about 300 ms.
Why does an async function inside forEach not hold up the next line?Tap to reveal
- forEach ignores what its function returns.
- So nobody waits for the promise.
Because forEach ignores the promises.
Did you know?
Six at a time
Starting jobs together has a limit inside the browser. Chrome's DevTools reference lists one reason a request waits in a queue: there are already six TCP connections open for this origin, which is the limit, a rule that applies to HTTP/1.0 and HTTP/1.1 only. So a hundred requests started together to an old server still go about six at a time.
Why it fits here: It answers this topic's question: requests started together to one HTTP/1.1 server still run about six at a time.
A request with a deadline
A job awaited with others can be given a deadline. AbortSignal.timeout(ms) returns a signal that aborts by itself after the given time, with a TimeoutError; passed to fetch, it stops a slow request. MDN shows it working across browsers since April 2024, and the DOM standard defines the steps that make the signal.
Why it fits here: It adds a guard to this topic's Promise.all: one slow job can be given a time limit, so the whole group need not wait for ever.
In one line
await in order when a step needs the one before it; start independent jobs together and await Promise.all, which is as slow as the slowest job, not the sum. forEach does not wait for async functions.
await outside a function
At a glance
Most await lives inside async functions. Modules may also use it at the very top of the file, which is handy for loading settings before anything else runs.
A module with top-level await holds up the modules that import it until its promise settles. A slow module at the top slows every module that imports it. An ordinary script cannot use it there, but it can wrap the work in an async arrow called at once. And import() loads a module later, giving back a promise for it.
Take a guess: When did Node.js let modules use await at the top without a special flag?
Some blocks on this page have used await with no function around it. That worked because the Run button wraps your code in an async function. A real page is stricter, and the rule depends on what kind of script it is.
An ordinary script may not use await at its top level:
On a real site, in an ordinary script
<!DOCTYPE html>
<title>Clock Tower</title>
<script>
const menu = await Promise.resolve("thali");
console.log(menu);
</script>
The Console shows
Error Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules
The message itself says where await is allowed: in async functions, and at the top level of a module. Mark the same script as a module, and it runs:
On a real site, in a module
<!DOCTYPE html>
<title>Clock Tower</title>
<script type="module">
const menu = await Promise.resolve("thali");
console.log(menu);
</script>
The Console shows
Info thali
await written outside any function, at the top level of a module. The module pauses there, and the modules that import it wait until it has finished.
That last point matters. A module that awaits something at its top level holds up everything that imports it, so an importer always sees finished exports:
config.js
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
console.log("config starts");
export const RATE = await wait(50, 18);
console.log("config ready");
main.js
import { RATE } from "./config.js";
console.log("main sees", RATE);
On a real site, served with the files above
<!DOCTYPE html>
<title>Clock Tower</title>
<script type="module" src="main.js"></script>
The Console shows
Info config starts
Info config ready
Info main sees 18
main.js could not start until config.js had finished, so RATE was ready when main.js read it. Node does the same in a module, as this .mjs file shows:
rate.mjs
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
const rate = await wait(10, 18);
console.log(`GST is ${rate}%`);
Terminal
/home/asha/shop$ node rate.mjs
GST is 18%
In an ordinary script
An ordinary script can still use await inside a function. A common shape is an async arrow that is called at once, the async cousin of the IIFE in the scope lesson:
On a real site, in an ordinary script
<!DOCTYPE html>
<title>Clock Tower</title>
<script>
(async () => {
const menu = await Promise.resolve("thali");
console.log(menu);
})();
</script>
The Console shows
Info thali
Loading a module later
The modules lesson left one thing for now. import("./file.js"), written like a function call, loads a module when the line runs, and gives a promise of its exports. So await can wait for it, and destructuring can unpack it:
prices.js
export function withGst(price) {
return (price * 118) / 100;
}
main.js
console.log("page ready");
const { withGst } = await import("./prices.js");
console.log(withGst(100));
On a real site, served with the files above
<!DOCTYPE html>
<title>Clock Tower</title>
<script type="module" src="main.js"></script>
The Network panel shows
200 document /
200 script /main.js
200 script /prices.js
The Console shows
Info page ready
Info 118
page ready printed first: nothing in main.js had to wait for prices.js to start. A page can keep a rarely used feature, such as a chart, out of its first load, and bring it in when somebody asks.
| Where | await allowed? | Why |
|---|---|---|
| inside an async function | yes | that is what async is for |
| at the top level of a module | yes | the module pauses, and its importers wait |
| at the top level of an ordinary script | no: a SyntaxError | ordinary scripts cannot pause |
| inside a plain function, even in a module | no: a SyntaxError | the function is not async |
| at the top of a block on this page | yes | the Run button wraps it in an async function |
Worked example 5
The canteen's page needs the day's dishes before it can show anything. Put the slow loading in a module of its own, so that main.js can use the dishes as a finished value.
What we have: a slow load, and a main file that needs its result
What we need: main.js written as if the dishes were already there
The plan: menu.js exports the awaited list with top-level await; main.js imports it, and waits without saying so
menu.js
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
export const dishes = await wait(40, ["thali", "poha"]);
main.js
import { dishes } from "./menu.js";
console.log(`Today: ${dishes.join(", ")}`);
On a real site, served with the files above
<!DOCTYPE html>
<title>Clock Tower</title>
<script type="module" src="main.js"></script>
The Console shows
Info Today: thali, poha
main.js prints Today: thali, poha, with no await of its own.
Check: dishes was an array, not a promise, by the time main.js ran.
A path that fails: a long top-level await for something the page could show without. Every module that imports it waits too, so one slow server holds up the whole page. Keep such waits for what truly must come first.
When you are stuck: await is refused outside a function
await is only valid in async functions and the top level bodies of modules: add type="module", or wrap the code in an async function.
It works in a block here and not in your page? The Run button wraps blocks; your page does not.
A plain function inside a module still needs async.
A page stuck on one module may be held up by another module's top-level await.
Your turn
A page has <script>const x = await f();</script>. What does the Console say, and what is the shortest fix?Tap to reveal
- An ordinary script may not use await at its top level.
- Marking the script as a module allows it.
SyntaxError: await is only valid...; add type="module".
A module uses top-level await for 2 seconds. What happens to a module that imports it?Tap to reveal
- Importers wait until the module has finished.
It waits too, so its code starts after those 2 seconds.
What does import("./prices.js") give?Tap to reveal
- It is written like a call, and loads the module when the line runs.
A promise of the module's exports.
Did you know?
await in the Console, 2017
The browser's Console allowed await on its own line years before modules did. Chrome's notes on DevTools in Chrome 62, last updated in August 2017, announce support for top-level await operators in the Console. So typing await fetch(url) there works without an async function around it. Modules gained the same freedom later, as this topic shows.
Why it fits here: It gives a handy use of this topic's top-level await: in the browser's Console, await works on a line of its own.
Source: Chrome for Developers: What's New In DevTools (Chrome 62)
No flag since August 2020
Node.js let modules use top-level await without a flag in version 14.8.0. Its release notes, updated on 11 August 2020, list the change as module: unflag Top-Level Await, by Myles Borins, who also championed the proposal. Before that, the feature needed a special command-line flag to switch it on.
Why it fits here: It answers this topic's question: Node.js ran top-level await without a flag from version 14.8.0, in August 2020.
Source: Node.js blog: Node.js 14.8.0
In one line
At the top level, await is allowed in a module, where it holds up the modules that import it, and not in an ordinary script, which can use an async arrow called at once. The call import() loads a module later and gives a promise.
Values that arrive slowly
At a glance
A long train of goods wagons passes a crossing one wagon at a time; nobody waits for the whole train to be loaded first. Some values arrive in the same way, a page of results at a time.
An async generator, written async function*, can await between the values it yields, and for await...of waits for each value in turn. Values are asked for one at a time, so a break stops the work, and pages that nobody needs are never fetched.
Take a guess: Can Node.js streams be read with for await...of?
A generator hands out values one at a time, and an async function can wait. Put the two together, and you get an async generator: a function that can wait between its values. It suits data that comes in pieces, such as a long list that a server sends one page at a time.
A function written async function* name() { ... }. Inside it, both await and yield may be used. Each value it yields can take as long as it needs to arrive.
A loop that walks an async generator, or any list of promises, waiting for each value before it runs the body with it. It may be used wherever await may.
async function* lines() {
yield "one";
yield "two";
}
for await (const line of lines()) console.log(line);
one
two
So far it looks like an ordinary generator. The new part is that the generator may wait before each value, and the loop waits with it:
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
async function* slowCount(n) {
for (let i = 1; i <= n; i++) {
await wait(10);
yield i;
}
}
let sum = 0;
for await (const x of slowCount(3)) sum += x;
console.log(sum);
6
Behind the loop, the protocol is the one from the iterators lesson, with one change: next gives a promise of the { value, done } object, so each step can be awaited.
async function* g() {
yield 1;
}
const it = g();
const first = await it.next();
console.log(first, (await it.next()).done);
{ value: 1, done: false } true
for await...of also walks an ordinary array of promises, awaiting each in the order of the array, whichever finishes first:
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
for await (const v of [wait(40, "a"), wait(5, "b")]) console.log(v);
a
b
| Generator | Async generator | |
|---|---|---|
| written | function* g() | async function* g() |
| may wait inside | no | yes, with await |
| next gives | { value, done } | a promise of { value, done } |
| walked with | for...of | for await...of |
Worked example 6
A server gives the day's orders one page at a time. A screen shows orders until it finds the first order of vada, and should ask the server for no more pages than it needs. Write an async generator over the pages, and stop the loop at vada.
What we have: pages that are slow to arrive, and a point at which to stop
What we need: orders shown up to vada, and no extra page asked for
The plan: an async generator awaits one page at a time and yields its orders; the loop breaks at vada, which stops the generator
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
const pages = [["tea", "dosa"], ["vada"], ["idli"]];
async function getPage(n) {
console.log(`asking for page ${n}`);
await wait(10);
return pages[n - 1];
}
async function* allOrders() {
for (let n = 1; n <= pages.length; n++) {
for (const order of await getPage(n)) yield order;
}
}
for await (const order of allOrders()) {
console.log(order);
if (order === "vada") break;
}
asking for page 1
tea
dosa
asking for page 2
vada
The screen shows tea, dosa and vada, and page 3 is never asked for.
Check: no line says asking for page 3, because the generator stops when the loop breaks.
A path that fails: loading every page first into one big array, then looping. The screen waits for all the pages, and asks the server for pages it never needed.
When you are stuck: for await does not work
Unexpected reserved word means for await in a plain function: it is allowed only where await is, in an async function or at a module's top level.
An async generator needs both words: async function*.
g is not a function or its return value is not iterable, for an async generator, means a plain for...of or a spread: use for await...of.
Use break to stop early: the generator stops too.
Your turn
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
async function* g() {
yield await wait(10, "a");
yield await wait(1, "b");
}
const got = [];
for await (const v of g()) got.push(v);
console.log(got);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
[ 'a', 'b' ]
- Each yield waits for its own value.
- The second value is asked for only after the first.
It prints [ 'a', 'b' ].
What does next() give for an async generator?Tap to reveal
- Each step may take time.
A promise of { value, done }.
Why does a break in for await...of save work?Tap to reveal
- The generator makes values only when asked.
- After the break, nobody asks.
Because the generator stops, so later pages are never fetched.
Did you know?
Streams you can walk
Node.js streams can be read with this topic's loop. Its documentation lists readable[Symbol.asyncIterator](), added in version 10.0.0, so for await...of can read a file stream chunk by chunk. If the loop ends with a break, a return or a throw, the documentation says, the stream is destroyed, so nothing more is read.
Why it fits here: It answers this topic's question: Node's readable streams are async iterables, so for await...of reads them piece by piece.
Source: Node.js documentation: Stream
Collecting it all at once
Collecting every value of an async source into an array has its own method. MDN describes Array.fromAsync() as creating a new array from an async iterable, an iterable or an array-like object, and shows it working across browsers since January 2024. TC39's list of finished proposals names it, by J. S. Choi.
Why it fits here: It gives the other end of this topic's async generators: when every value is wanted, one call collects them all.
In one line
An async generator, async function*, can await between its values, and for await...of waits for each one. Values are asked for one at a time, so a break stops the work, and pages that nobody needs are never fetched.
Where it is used
Most new code that waits for anything is written with async and await. Here is where each idea of this lesson does its work.
| What you learned | Where it is used | A real example |
|---|---|---|
| async functions | anything that loads, saves or sends | getFare, which will soon ask a server |
| await in order | steps that need each other | the seat, then the payment, then the ticket |
| try, catch and finally | failures, and clearing up either way | hiding a loading sign whatever happens |
| Promise.all with await | independent pieces of a page | marks and attendance loaded side by side |
| top-level await | modules that must finish before others start | settings loaded before the page's code runs |
| import() | features loaded only when wanted | a chart brought in when somebody opens it |
| async generators | data that comes in pieces | a long list, one page at a time |
Mistakes and debugging
These are the slips that people meet most often with async and await. Every output below is the real one, from the code shown.
1. A forgotten await
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
async function total() {
const price = wait(10, 100);
return price + 18;
}
console.log(await total());
[object Promise]18
No error: price is a promise, and + turned it into text. The fix: const price = await wait(10, 100);.
2. await in a function that is not async
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
function load() {
const menu = await wait(10, "thali");
return menu;
}
Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules
The fix: async function load(), and await its call in turn.
3. A try that does not cover the failure
async function save() {
throw new Error("disk full");
}
try {
save();
} catch (e) {
console.log("caught", e.message);
}
Uncaught Error: disk full
at save (line 2)
at line 5
The call gave back a rejected promise, and nothing was thrown inside the try. The fix: await save();.
4. Promises where values were wanted
const doubled = [1, 2].map(async (n) => n * 2);
console.log(doubled.join());
[object Promise],[object Promise]
No error: an async function gives a promise, so map made an array of promises. The fix: await Promise.all([1, 2].map(async (n) => n * 2)).
5. await on the wrong thing
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
console.log(await wait(5, [1, 2]).length);
console.log((await wait(5, [1, 2])).length);
undefined
2
No error: the dot comes first, so the first line asked the promise for its length, and awaited undefined. The fix: round brackets around the await, as on the second line.
6. Everything awaited in a row
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
const menu = await wait(20, "menu");
const prices = await wait(20, "prices");
console.log(menu, prices);
menu prices
No error, and no wrong answer: only a page that takes twice as long as it should. The fix: const [menu, prices] = await Promise.all([wait(20, "menu"), wait(20, "prices")]);.
The debugging corner: find the missing await
Text such as [object Promise], a value of undefined, or a line that runs too early usually means one await is missing. Print the value with value instanceof Promise beside it. For a failure that nobody catches, read the trace: it names the async function, so the fix is at its call.
Quick card
The whole lesson on one card. Come back to it whenever you need a reminder.
The lesson in code
const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
// async gives a promise; await pauses this function only
async function book(seatFree) {
try {
const seat = await wait(10, "seat 42");
if (!seatFree) throw new RangeError(`${seat} is taken`);
return await wait(10, `${seat} booked`); // return await, inside a try
} catch (err) {
return `Sorry: ${err.message}`;
} finally {
console.log("sign off");
}
}
console.log(await book(true));
console.log(await book(false));
// independent jobs together; values in the order of the inputs
const [menu, prices] = await Promise.all([wait(30, "menu"), wait(10, "prices")]);
console.log(menu, prices);
// values that arrive slowly
async function* pages() {
yield await wait(5, "page 1");
yield await wait(5, "page 2");
}
for await (const page of pages()) console.log(page);
sign off
seat 42 booked
sign off
Sorry: seat 42 is taken
menu prices
page 1
page 2
| When you see | It means | Look at |
|---|---|---|
[object Promise] in text | a forgotten await | await the value first |
SyntaxError: await is only valid in async functions ... | await in a plain function or an ordinary script | async, or a module |
Uncaught Error in spite of a try | a call in the try was not awaited | await inside the try |
| a line after forEach that runs too early | forEach does not wait | for...of, or Promise.all with map |
undefined from await p.length | the dot came before the await | round brackets around the await |
| a page that loads slowly | independent awaits in a row | Promise.all |
The story: Top to bottom
You rewrite the fitting as one async function. Each step stands on its own line with await in front of it, and the function pauses there while the rest of the floor carries on. One try wraps all the steps, and one catch writes any failure in the log. The grease and the key do not depend on each other, so you send for those two together, and await them both.
The fitting now reads like a page of instructions, and takes less time than before.
Master Verge reads it once, without his finger, and nods. "Nothing changed underneath," he says. "It is promises all the way down. It only reads as it should."
Reagents gathered: async function, await, top-level await, sequential, concurrent, for await...of.
Sources
- MDN Web Docs (Prose CC BY-SA 2.5 or later; code samples added since 2010-08-20 CC0 (its licensing page, read 2026-10-26); reused with credit)
- The ECMAScript language specification (ECMA-262) (Ecma International copyright; facts and ideas only)