Write an async function that waits for a promise with await and uses its value on the next line. See that an async function always gives back a promise, that await pauses only the function it is written in while the rest of the file goes on, and why await needs async, then rewrite TaskKit’s remind so its wait reads from top to bottom.
Fundamentals
TypeScript
`async` / `await`. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
At the end of the last lesson TaskKit's remind worked: it said
Reminder set: Call Mom at once and Reminder: Call Mom two seconds
later. Read its code, though, and its lines are not in the order they
run. The line that runs last sits in the middle of the case, inside a
then callback, and the lines under it run first.
A recipe does not read like that. It says "bake for twenty minutes,
then take the cake out", one step under the other, in the order you
do them. In this lesson you write code that reads the same way, with
two words, async and await, and the wait in TaskKit's remind
moves into a small function that reads from top to bottom.
await: wait here for the value
In lesson 11.3 a promise was the buzzer, and then said what to do
once it buzzed. await does that job without a callback: written
before a promise, it waits until the promise is fulfilled and gives you
what the promise holds. On a Promise<string> it gives you a string.
Here is brew from the last lesson, and a function that waits for
it. Make brew.ts in ~/projects/taskkit:
brew.tsts
function brew(): Promise<string> { return new Promise((resolve) => { setTimeout(() => { resolve("Flat white"); }, 1000); });}async function serve(): Promise<void> { const drink = await brew(); console.log("Ready:", drink);}serve();
Line 9 reads like a recipe: wait for brew()'s promise, then keep
what it holds in drink. Line 10 runs only once that has happened,
so drink is the string, with no callback around it. await works
only inside a function marked async, the word in front of
function on line 8; the next section is about what that word
changes. node brew.ts prints this a second later:
Outputtext
Ready: Flat white
In VS Code (Visual Studio Code, your editor), rest the pointer on
drink in brew.ts. The figure sets it beside the line from 11.3 that
kept the promise in order:
Without await: the promise
Does: Holds the promise as soon as brew() returns
Never: Never holds the string itself
With await: the value
Does: Holds the string, once the promise is fulfilled
Never: Never holds the promise
Without await the box holds the promise; with it, the value
async: a function that gives back a promise
A function that waits cannot hand back its answer the moment it is
called, because the answer is not there yet. So an async function
always gives back a promise, whatever its return says:
The body returns 3, a number, and the function gives back a
Promise<number>, fulfilled with 3. That is why the return type
of an async function is always Promise<…>: Promise<number>
here, Promise<void> for serve, which returns nothing and only
says "done". An async function needs no new Promise: return
fills its promise for you.
To get the 3 back out, you treat countTasks() like any promise:
with then, as on line 4, or with await countTasks() inside another
async function. Press Run: it prints 3 tasks.
What await pauses, and what it does not
In lesson 5.8 a caller paused mid-line while the function it called
ran, and stayed on the call stack the whole time. await pauses too,
but differently: the async function steps off the stack, the code
that called it goes on, and the function goes on from await, with
the promise's value, once the promise is fulfilled. Make remind.ts:
ms is short for milliseconds, thousandths of a second: delay(2000)
waits two seconds. Press Next step to walk through it, or let it
play:
Callstack
Timer
Promise
Terminal
Call stack: remindremindremind
Terminal: Reminder set: Call Mom
All 11 steps shown.Step 1 of 11: Call stack: remindStep 2 of 11: Terminal: Reminder set: Call MomStep 3 of 11: Call stack: awaitStep 4 of 11: Timer: 2 secondsStep 5 of 11: Promise: pendingStep 6 of 11: Call stack: line 12Step 7 of 11: Terminal: Back to the listStep 8 of 11: Call stack: emptyStep 9 of 11: Promise: fulfilledStep 10 of 11: Call stack: remind, line 9Step 11 of 11: Terminal: Reminder: Call Mom
All 11 steps shown.
When remind steps off the stack at line 8, it gives line 11 a
pending promise, the Promise<void> its return type names, and line
11 does nothing with it. await pauses only the function it is
written in: had line 11 been await remind("Call Mom"); inside another
async function, that function would have waited for all of remind,
its two seconds included. Check it with npm run check, the script npm
(Node package manager) runs for TaskKit, and run it:
The check prints only its two > lines. Node prints the first two
lines at once and the last one two seconds later:
Predict the second line
This time nothing waits on a timer: countTasks returns 3 at once,
so its promise is fulfilled the moment it is made. report awaits it
all the same.
Predict
What is the second line this program prints?
The common mistake: await without async
When you write await on a line, it is easy to forget that the
function around it must be marked async.
Common mistake
Waiting in a function that is not async
In remind.ts, take async off line 6 and give it the return type of
a function that returns nothing:
npm run check prints its two > lines, and then this:
The check points at two places. TS1308 is its error code, TS for
TypeScript, then the number of this kind of mistake (lesson 1.5). It
points at line 8, where await is, and line 6, the function that
would have to allow it.
'await' expressions are only allowed within async functions and at the top levels of modules.
The fix
Mark the function async, and give it the return type every async
function has, a promise: Promise<void>, because it returns nothing.
Add async but keep : void, and the check stops you again, this
time at the return type, because an async function gives back a
promise:
"The global Promise<T>" is the one built into JavaScript, the one
you have used since lesson 11.3. The first message also names "the top
levels of modules": TaskKit's files are modules (lesson 9.1), and
there await also works outside any function, at the top of the
file. Until Module 12, every await here sits inside an async
function, where it pauses only that function. At the top of a file no
function is around it, so it pauses the rest of the file: the lines
below it wait. Lesson 12.2 uses it there.
Next time the check says TS1308, look up from the await to the
function line above it: it needs async, and its return type a
Promise<…>.
TaskKit: remind with await
Now TaskKit's step. The remind case keeps its loop, and the waiting
moves into a small async function that reads top to bottom.
1
Add remindLater to index.ts
In ~/projects/taskkit/index.ts, add this function under
messageOf:
2
Call it from the remind case
In the remind case, replace the three lines of delay(2000).then(…)
with one call, so the case reads:
The loop calls remindLater for each title and goes on at once:
each call pauses at its own await; the loop does not pause.
3
Check, run TaskKit, run the tests
The check prints only its two > lines. TaskKit prints what it
printed in the last lesson, everything but the last line at once and
the last line two seconds later:
Same output, clearer code: the wait and what follows it now stand one
under the other, in remindLater. npm test ends with ℹ pass 10 and
ℹ fail 0, as before.
Pass all four tasks to complete the lesson with practice. Reach the end without them and it counts as read only.
Exercises
Each one is checked in your browser. Try it before you open the hints;
they come one at a time.
Recap
Recap · 3 questions
Check yourself
What does await give you on a Promise<string>?
Check yourself
In which functions can you write await?
Check yourself
What does await pause, inside an async function?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
async / await
What things are
Word
What it means
await
Waits for a promise, then gives you what it holds
async function
A function that may wait; it gives back a promise
Code
Write
To
async function serve()
Mark a function that uses await
: Promise<void>
The return type of one that returns nothing
const drink = await …
Wait, then keep the value in a box
return 3;
Fulfil the async function's promise with 3
remindLater(reminder);
Call an async function, go on at once
Rules
Rule
What it means
await needs async
In any other function the check stops you: TS1308
The type says Promise<…>
async with : number is TS1064
In a function, it pauses that function
The caller and the file go on
The line after await waits
Even when the promise is already fulfilled
Where to go next
You can now write an async function, wait for a promise with
await and use its value on the next line, and say in which order such
code prints. The wait in TaskKit's remind now reads from top to
bottom.
Next is Errors in async code: try around await. Every
promise so far was fulfilled or stayed pending; that lesson is about
the third state, rejected, and what await does when the wait goes
wrong.
Before you move on, add a second wait to remindLater: after the
Reminder: line, await delay(1000); and a line that prints
Reminder again: with the task. Predict what
npm start remind "call Mom" "buy milk" prints and when, then run
it, and take the two lines out again. Then delete brew.ts and
remind.ts from the taskkit folder: they are not part of TaskKit.
Reminderset:CallMom
Reminderset:CallMom
Call stack: awaitawaitawait
Timer: 2 seconds2seconds2seconds
Promise: pendingpendingpending
Call stack: line 12line12line12
Terminal: Back to the listBacktothelistBacktothelist
Call stack: emptyemptyempty
Promise: fulfilledfulfilledfulfilled
Call stack: remind, line 9remind,line9remind,line9
Line 11 calls remind, and line 7 prints its first line.
Line 7's text is out before any wait.
Line 8 calls delay and waits for its promise. remind pauses
and leaves the stack.
Node counts the 2 seconds outside your code.
delay's promise: the wait is not over, so await waits on it.
Back in the file, line 12 prints. The file is done.
Line 12's text is out while remind waits.
The stack is empty while the timer counts. remind is waiting,
off the stack. Its last moment, when the timer's callback
resolve runs, is too short to draw.
The timer's callback, resolve, runs and fulfils the promise.
The promise is fulfilled, so remind goes on after await, with
task still "Call Mom".
Line 9 prints. Nothing is left to wait for, so Node ends.
At await, remind steps off the stack and comes back later
Exercise · Read the code
What the check asks for
The check stops at line 5 with TS1308. Which word is missing on line 4?
Exercise · Read the code
One reminder after the other
remind works like the one in remind.ts, with shorter messages and a
one-second wait, and delay is above it as before. This time main
awaits each call. In which order does node print?
Outputtext
Reminder set: Call MomBack to the listReminder: Call Mom
What the check printstext
remind.ts:8:3 - error TS1308: 'await' expressions are only allowedwithin async functions and at the top levels of modules.8 await delay(2000); ~~~~~ remind.ts:6:10 - Did you mean to mark this function as 'async'? 6 function remind(task: string): void { ~~~~~~Found 1 error in remind.ts:8
What the check printstext
remind.ts:6:38 - error TS1064: The return type of an async function ormethod must be the global Promise<T> type. Did you mean to write'Promise<void>'?6 async function remind(task: string): void { ~~~~Found 1 error in remind.ts:6
What TaskKit printstext
> start> node index.ts remind call Mom┌ TaskKit 0.1 ───────────────┐│Your tasks, in your terminal│└────────────────────────────┘Reminder set: Call Mom0 tasks added, room for 5 moreList 0% fullYour list, A to Z:Reminder: Call Mom
function delay(ms: number): Promise<void> { return new Promise((resolve) => { setTimeout(resolve, ms); });}async function remind(task: string): Promise<void> { console.log("Reminder set:", task); await delay(2000); console.log("Reminder:", task);}remind("Call Mom");console.log("Back to the list");
bash
npm run checknode remind.ts
ts
async function countTasks(): Promise<number> { return 3;}async function report(): Promise<void> { console.log("Counting"); const count = await countTasks(); console.log(`${count} tasks`);}report();console.log("Back to the list");
remind.tsts
function delay(ms: number): Promise<void> { return new Promise((resolve) => { setTimeout(resolve, ms); });}function remind(task: string): void { console.log("Reminder set:", task); await delay(2000); console.log("Reminder:", task);}remind("Call Mom");console.log("Back to the list");
remind.tsts
function delay(ms: number): Promise<void> { return new Promise((resolve) => { setTimeout(resolve, ms); });}async function remind(task: string): Promise<void> { console.log("Reminder set:", task); await delay(2000); console.log("Reminder:", task);}remind("Call Mom");console.log("Back to the list");
index.tsts
async function remindLater(reminder: string): Promise<void> { await delay(2000); console.log("Reminder:", reminder);}
index.tsts
case "remind": for (const title of command.titles) { const reminder = capitalize(title.trim()); console.log("Reminder set:", reminder); remindLater(reminder); } break;
bash
npm run checknpm start remind "call Mom"npm test
Exercise · Fix the error
Name the promise
This program should print 2 tasks done, but the check stops it at
line 1 with TS1064:
Fix the return type.
Loading the editor…
Exercise · Write the code
From then to await
This is the tea from the last lesson, served with then. Rewrite the
last three lines: write an async function serveTea that awaits
brewTea() and prints Ready: Green tea, and call it.
Loading the editor…
text
The return type of an async function or method must be the globalPromise<T> type. Did you mean to write 'Promise<number>'?