Learn what a promise is: an object a function gives back at once, standing for a result still to come, pending until it is fulfilled. Make one with new Promise and resolve, run code with its value in then, read Promise<T> the way you read Array<T>, and give TaskKit a delay() helper and a remind command that waits before it prints.
TypeScript
Fundamentals
`Promise<T>`. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
Back in the café from the last lesson, at the counter this time. You
order a flat white, and the cashier does not keep you standing there
while it is made: you get a small buzzer at once and sit down. A few
minutes later it buzzes, and you collect your coffee. The buzzer is
not the coffee. It stands for coffee still to come, and it tells you
when the coffee is ready.
JavaScript, and so TypeScript, has the same thing for a result that
takes time: a promise. In this lesson you make your own, run code once
its result is ready, and give TaskKit a delay() helper and a
remind command that waits before it prints.
A value that comes later
A function gives its answer back with return, and the line that
called it can use the answer straight away. A function that waits
cannot: when it returns, the wait has only just started. In lesson
11.1 the answer was a callback. Whatever needs the result goes inside
the callback, because only there does the result exist.
A promise is the other way. It is an object a function can return
at once, and it stands for a result still to come, the way the buzzer
stands for your coffee. A promise is always in one of three states:
pending: the wait is not over yet;
fulfilled: the wait is over, and the result is in the promise;
rejected: the wait went wrong, like a café that has run out of
milk. Lesson 11.5 deals with that one.
A promise starts pending and changes state only once: a fulfilled
promise stays fulfilled.
Promise<T> reads the way lesson 10.1 read Array<T>: Promise is
the type, and its slot T says what the promise holds once it is
fulfilled. A Promise<string> will hold a string; a
Promise<string[]>, a list of strings. A Promise<void> holds
nothing. Like a function that returns void (lesson 5.6), it only
says "done". The cheat sheets of Module 5 said a return type
"promises" what comes out; that was the everyday word, and from here
on a promise is this object.
Making one: delay()
The simplest promise is fulfilled after a wait and holds nothing, a
Promise<void>. This function makes one; its parameter ms is how long
to wait, in milliseconds (ms), thousandths of a second:
reminder.tsts
function delay(ms: number): Promise<void> { return new Promise((resolve) => { setTimeout(resolve, ms); });}
new Promise(…) makes a promise, the way new Map() made a Map in
lesson 6.10. It takes one function, the arrow function on line 2, and
runs it at once. The promise cannot know when your wait will end, so it
hands that function a way to tell it: resolve, a function that
fulfils the promise when you call it. Until something calls resolve,
the promise stays pending.
Line 3 hands resolve to setTimeout as its callback. When the time
is up, resolve runs like any timer's callback (lesson 11.2), and the
promise is fulfilled. So delay(2000) gives back a pending promise at
once, and that promise is fulfilled two seconds (2000 ms) later.
then: what to do once it is fulfilled
Every promise has a method, then, that takes a callback: what to
do once the promise is fulfilled. then does not wait. It keeps the
callback in the promise and returns, and the lines after it run on.
Here is the whole of reminder.ts:
Line 6 calls delay and keeps the promise in reminder, line 7 hands
it a callback, and line 10 prints. Press Next step to walk
through it, or let it play:
Line 6 calls delay. It starts a 2-second timer and gives back a
promise at once.
Node counts the 2 seconds outside your code. Then the timer's
callback, resolve, runs.
The promise in reminder stands for a wait that is not over yet.
Line 7 hands the promise a callback for later. Nothing runs yet.
Line 10 prints. The file is done.
Line 10's text is out, while the promise is still pending.
The stack is empty while the timer counts. Its last moment, when
the timer's callback resolve runs, is too short to draw.
The 2 seconds are up: the timer's callback, resolve, runs and
fulfils the promise.
The promise is fulfilled, so the callback from line 7 runs.
The callback prints. Nothing is left to wait for, so Node ends.
The callback runs once the promise is fulfilled
All 10 steps shown.Step 1 of 10: Call stack: delayStep 2 of 10: Timer: 2 secondsStep 3 of 10: Promise: pendingStep 4 of 10: Call stack: thenStep 5 of 10: Call stack: line 10Step 6 of 10: Terminal: Reminder setStep 7 of 10: Call stack: emptyStep 8 of 10: Promise: fulfilledStep 9 of 10: Call stack: callbackStep 10 of 10: Terminal: Reminder: call Mom
All 10 steps shown.
Watch the Promise lane: it is pending while the timer counts and
fulfilled once resolve runs. Like a timer's callback in the last
lesson, the then callback still waits for an empty stack.
As in the last two lessons, you make the programs in ~/projects/taskkit
and run them with Node. Make reminder.ts with the ten lines above,
then check it with npm (Node package manager, the tool that runs the
project's scripts) and run it:
bash
npm run checknode reminder.ts
The check prints only its two > lines. Node prints the first line at
once and the second two seconds later:
Outputtext
Reminder setReminder: call Mom
A promise that carries a value
delay's promise holds nothing. A promise can also hold a result, and then
hands that result to its callback. To fulfil a Promise<string>,
call resolve with the string. Make brew.ts:
brew.tsts
function brew(): Promise<string> { return new Promise((resolve) => { setTimeout(() => { resolve("Flat white"); }, 1000); });}const order = brew();order.then((drink) => { console.log("Ready:", drink);});console.log("Order placed");
After a second, resolve("Flat white") fulfils the promise with the
string, and then passes that string to its callback as drink.
node brew.ts prints:
Outputtext
Order placedReady: Flat white
Rest the pointer on order in VS Code (Visual Studio Code, your
editor), then on drink:
Does: Gets the string, once the promise is fulfilled
Never: Never gets the promise itself
T is what the promise holds, and what then hands the callback
You never write the type of drink. TypeScript reads it from T:
brew() gives back a Promise<string>, so then hands its callback
a string.
Predict what the box holds
peek.ts keeps the first six lines of reminder.ts; line 7 prints the
box itself, right after delay(2000) has returned.
Predict
What does line 7 print in your terminal?
peek.tsts
function delay(ms: number): Promise<void> { return new Promise((resolve) => { setTimeout(resolve, ms); });}const reminder = delay(2000);console.log(reminder);
The common mistake: the promise as the value
A promise looks like the result in the code, so it is easy to use it
as if it were the result.
Common mistake
Reading the list before it is there
Make load.ts. loadTasks gives back a promise of a list of tasks,
fulfilled a second later, the way reading a file will be in Module 12.
The last line counts the tasks:
npm run check prints its two > lines, and then this:
What the check printstext
load.ts:9:22 - error TS2339: Property 'length' does not exist on type'Promise<string[]>'.9 console.log(`${tasks.length} tasks`); ~~~~~~ load.ts:9:22 - Did you forget to use 'await'? 9 console.log(`${tasks.length} tasks`); ~~~~~~Found 1 error in load.ts:9
The error has a code, TS2339 (TS for TypeScript, then the number of
the error). tasks holds the promise, not the list, and a promise has
no length. TypeScript catches it: run node load.ts anyway, and Node
prints undefined tasks.
Property 'length' does not exist on type 'Promise<string[]>'.
You can call then right on what loadTasks() gives back,
loadTasks().then(…), with no box in between. The check passes, and
node load.ts prints 2 tasks a second later.
You can recognise it by a type in the error that starts with
Promise<: the code asks the promise for something only its value
has. The line Did you forget to use 'await'? points at the next
lesson; until then, the answer is then.
TaskKit: delay() and a reminder
Now TaskKit's step: a remind command that prints its reminder two
seconds later, built on delay.
1
Put delay in its own file
In ~/projects/taskkit, make time.ts with delay, exported so
index.ts can import it (lesson 9.1):
time.tsts
export function delay(ms: number): Promise<void> { return new Promise((resolve) => { setTimeout(resolve, ms); });}
2
Teach readCommand the new word
In command.ts, add a line to the Command union, under the add
one:
command.tsts
| { kind: "remind"; titles: string[] }
Then add a case to the switch, above case "help"::
command.tsts
case "remind": return { kind: "remind", titles: titles };
Last, make the hint for a command typed in capitals know the new word.
In the default: case, replace the if line that checks lower with
these six lines (the throw under it stays):
Each title gets its own promise and its own callback, and the for
loop does not wait for any of them.
4
Check, run TaskKit, run the tests
bash
npm run checknpm start remind "call Mom"npm test
The check prints only its two > lines. TaskKit prints everything but
the last line at once, and the last line two seconds later:
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
The summary and the list do not wait: they are the lines after the
switch, and they run while the promise is pending. npm test passes
as before. Try npm start Remind "call Mom" too: it prints Commands are in lower case. Try: remind, as it does for the other commands.
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.
Exercise · Read the code
What then hands over
ts
function countDone(): Promise<number> { return new Promise((resolve) => { resolve(2); });}countDone().then((done) => { console.log(`${done} tasks done`);});
What type does TypeScript give done?
Exercise · Fix the error
Count with the new one
This program should print 4 tasks with the new one, but the check
stops it with Operator '+' cannot be applied to types 'Promise<number>' and '1'. Fix it, so the count is used where it
exists.
Loading the editor…
Exercise · Write the code
Brew the tea
Finish brewTea: it gives back a promise fulfilled with the string
"Green tea" after half a second. Then call it, and print Ready: Green tea with then.
Loading the editor…
Exercise · Read the code
A promise nobody fulfils
Here the timer's callback prints, but nothing calls resolve. What
does node print when it runs this file?
The wait is over, and the result is in the promise
Rejected
The wait went wrong (lesson 11.5)
Code
Write
To
Promise<string>
The type of a promise that will hold a string
Promise<void>
The type of a promise that only says "done"
new Promise(…)
Make a promise; its function gets resolve
resolve("Flat white")
Fulfil the promise with that value
order.then((drink) => …)
Run the callback with the value, once ready
Rules
Rule
What it means
It comes back at once
A function that waits gives back a pending promise
Use the value in then
Only its callback has the value
then waits its turn
Its callback runs once the stack is empty
Promise<T> is not T
TypeScript stops .length on a promise
Someone calls resolve
A promise stays pending until something does
Where to go next
You can now write a function that gives back a promise, fulfil it with
resolve, and run code with its value in then, and TaskKit can set a
reminder that arrives two seconds later.
Next is async / await. It lets a function wait for a promise
on one line and go on with the value on the next, without a callback,
and TaskKit's remind will use it.
Before you move on, predict the order of the lines that
npm start remind "call Mom" "buy milk" prints, then run it to check.
Then delete reminder.ts, brew.ts, peek.ts and load.ts from the
taskkit folder: they are not part of TaskKit.