17.1 Why Some Work Waits
Before you start, set up a day17 folder the way Day 13 taught: run npm init -y, then npm install --save-dev typescript @types/node, add "type": "module" to package.json, and type the same tsconfig.json as on Day 1. @types/node matters more than ever today: it is what tells the checker about setTimeout and the other waiting tools in this lesson.
Every program so far has run the same way: line 1, then line 2, then line 3, each line finished before the next one starts, until the file ends. Code that runs like that, one step after another with nothing left for later, is called synchronous.
Some jobs, though, take time, and the time is spent waiting, not working. Reading a big file waits for the disk. Asking a web server for data waits for an answer to travel across the internet, which can take a second or more. A game waits for the next frame. If a program simply stood still during every wait, it could do nothing else: a web page would freeze while it loaded data, and a server could answer only one person at a time.
Think of ordering a pizza. You do not stand at the door staring until it arrives. You place the order, then set the table and pour drinks, and when the doorbell rings you deal with the pizza. JavaScript works the same way. Work that is started now and finished later, while the rest of the program carries on, is called asynchronous (“not at the same time”).
The simplest asynchronous tool is setTimeout(callback, ms), which asks JavaScript to call a function later: after at least ms milliseconds (thousandths of a second, so 1000 ms is one second). The function you pass is a callback, exactly Day 10’s idea: you hand it over, and someone else calls it when the time comes.
Worked example: Ordering a pizza
Read the lines in order, then compare them with the output.
console.log("Order placed");
setTimeout(() => {
console.log("Pizza is ready");
}, 1000);
console.log("Setting the table");
console.log("Pouring drinks");Order placed
Setting the table
Pouring drinks
Pizza is ready- Line 1 prints
Order placed. - Lines 2 to 4 are one statement: a call to
setTimeoutwith two arguments, an arrow function and1000. The call does not run the arrow function. It hands it to Node with a note saying “call this in one second,” and returns at once. - Lines 5 and 6 run immediately and print their messages.
- The file has now ended, but Node does not quit, because a timer is still waiting. About a second later, it calls the arrow function, which prints
Pizza is ready. Now nothing is left to wait for, and the program ends.
The part of Node that does this bookkeeping is called the event loop. It works in a cycle:
Two rules come out of this picture, and every example today follows them:
- Your file always runs to its end first. No callback can interrupt the line that is running. Even
setTimeout(callback, 0)waits until the file has finished. - One thing runs at a time. JavaScript never runs two pieces of your code at the same moment. Waiting happens side by side (many timers or downloads can be in progress at once), but running does not.
Key idea
Asynchronous work starts now and finishes later. setTimeout hands a callback to the event loop and returns at once;
the rest of the file runs first, and the callback runs when its time has come and nothing else is running.
Pause and try
Question 1 · Tracing
Predict exactly what this program prints, in order.
console.log("A");
setTimeout(() => {
console.log("B");
}, 500);
console.log("C");
setTimeout(() => {
console.log("D");
}, 0);
console.log("E");Check your reasoning
A
C
E
D
BThe file runs to its end first: lines 1, 5, and 9 print A, C, and E. The two setTimeout calls only hand their callbacks to the event loop. Then the timers run in the order they become ready: the 0 ms one (D) is ready at once, and the 500 ms one (B) half a second later. A delay of 0 does not mean “now”; it means “as soon as the file has finished.”
Reread 17.1 Why Some Work Waits if your order differed.
17.2 Callbacks That Run Later
Several timers can wait at the same time. Each one runs when its own time is up, so the order they were set in does not matter; only their delays do.
setTimeout(() => {
console.log("Toast is done (300 ms)");
}, 300);
setTimeout(() => {
console.log("Eggs are done (200 ms)");
}, 200);
setTimeout(() => {
console.log("Coffee is done (100 ms)");
}, 100);
console.log("Everything is cooking");Everything is cooking
Coffee is done (100 ms)
Eggs are done (200 ms)
Toast is done (300 ms)
The toast timer was set first, but it waits the longest, so it finishes last. All three wait together: the whole program takes about 300 ms, not 100 + 200 + 300 = 600 ms. Keep that in mind; it is the reason asynchronous code exists, and 17.7 comes back to it.
A function that does slow work can take a callback of its own, to say “when you are done, call this.” The callback can receive the result as an argument. Here boilWater takes a callback whose type, from Day 10, is (temperature: number) => void:
function boilWater(done: (temperature: number) => void): void {
console.log("Kettle on");
setTimeout(() => {
done(100);
}, 500);
}
boilWater((temperature) => {
console.log(`Water reached ${temperature} degrees`);
});
console.log("Getting out a cup");Kettle on
Getting out a cup
Water reached 100 degrees
Line 8 calls boilWater with an arrow function. boilWater prints Kettle on and sets a timer, then returns, so line 11 runs next. Half a second later, the timer’s callback calls done(100), which is the arrow function from line 8, with temperature set to 100. Notice that boilWater cannot return the temperature: by the time the water has boiled, boilWater finished long ago. The only way out for the result is through the callback.
Watch out
Reading a result before it exists. A beginner’s first try at getting a value out of a timer is to set a variable inside the callback and read it after setTimeout:
let message = "not ready";
setTimeout(() => {
message = "ready";
console.log(`Inside the callback: ${message}`);
}, 200);
console.log(`Right after setTimeout: ${message}`);Right after setTimeout: not ready
Inside the callback: readynpx tsc accepts this, and node runs it without a crash, but line 8 runs before the callback, because the file always runs to its end first. At that moment message still holds "not ready". The new value exists only from inside the callback onward. The fix is to put the code that needs the result inside the callback, or, from 17.4 on, to await it.
That fix has a cost. When step two needs step one’s result, and step three needs step two’s, each step goes inside the previous step’s callback:
function step(name: string, ms: number, next: () => void): void {
setTimeout(() => {
console.log(name);
next();
}, ms);
}
step("Boil the water", 300, () => {
step("Steep the tea", 200, () => {
step("Add milk", 100, () => {
console.log("Tea is ready");
});
});
});Boil the water
Steep the tea
Add milk
Tea is ready
It works, and the steps happen in order, but every new step pushes the code further right. Real programs also have to handle a failure at every step, which doubles the nesting. Programmers call this shape callback hell, and it is the problem the rest of today solves.
Pause and try
Question 2 · Short answer
In nested-callbacks.ts, the delays are 300, 200, and 100 ms, shortest last. Yet three-timers.ts showed that the shortest timer finishes first. Explain why nested-callbacks.ts still prints its steps in the order written, and about how long it takes.
Check your reasoning
Model answer: Each step call sets its timer only when the step before it has finished, because the next step call sits inside the previous one’s callback. So “Steep the tea” is not even started until “Boil the water” has printed. The timers never wait side by side, so the delays add up: about 300 + 200 + 100 = 600 ms.
A complete answer says the next timer is set inside the previous callback, so they run one after another, and that the total is the sum of the delays.
Reread 17.2 Callbacks That Run Later if your explanation differed.
Question 3 · Multiple choice
let total = 0; is followed by setTimeout(() => { total = 50; }, 100); and then console.log(total);. What does node print?
0500, then50a tenth of a second later- Nothing;
npx tscrejects changingtotalinside a callback
Check your reasoning
A. The console.log runs as soon as setTimeout returns, before the callback, so total is still 0. The callback changes total later, but nothing prints it afterward.
- B is wrong because it assumes the program waits at
setTimeout. It never does. - C is wrong: only one
console.logexists, and it ran already. Changing a variable does not print it. - D is wrong: a callback can change a
letvariable from outside it (a closure, from Day 10), and the checker allows it.
Reread 17.2 Callbacks That Run Later if you chose differently.
17.3 Promises: Values That Arrive Later
Callbacks force you to say up front, at the moment you start the work, what should happen with the result. It would be easier if a slow function could return something right away, and you could decide later what to do with it.
That something is a promise. Think of the buzzer a restaurant hands you when you order: it is not your food, but it stands for your food, and it will buzz when the food is ready, or if the kitchen has run out. A promise is an object that stands for a value that is not ready yet. Every promise is in one of three states:
| State | Meaning | Restaurant buzzer |
|---|---|---|
| pending | The work is still going on | Waiting; the buzzer is quiet |
| fulfilled | The work succeeded, and the promise holds a value | It buzzes: your food is ready |
| rejected | The work failed, and the promise holds an error | It buzzes: they have run out |
A promise starts pending and settles exactly once, into fulfilled or rejected. After that it never changes.
In TypeScript, a promise of a value of type T has the type Promise<T>, the generic type Day 14 previewed. A Promise<number> will one day hold a number; a Promise<string>, a string. A promise that only says “done” and carries no useful value is a Promise<void>.
You make a promise with new Promise(...), passing a function that receives a function called resolve. Calling resolve(value) fulfills the promise with that value. (The function also receives a second one, reject, for failures; 17.6 uses it.) Here is the most useful promise-making function there is, delay, which turns setTimeout into a promise:
Worked example: A promise that waits
function delay(ms: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
console.log("Waiting...");
delay(500).then(() => {
console.log("Half a second later");
});
console.log("This line does not wait");Waiting...
This line does not wait
Half a second later- Line 1:
delaytakes a number of milliseconds and returns aPromise<void>: it will fulfill, but with no value worth keeping. - Line 2:
new Promise(...)creates the promise. The arrow function inside runs straight away and receivesresolve. - Line 3:
setTimeout(resolve, ms)passesresolveitself as the timer’s callback (no parentheses: you hand the function over, you do not call it). When the timer runs out,resolveis called, and the promise becomes fulfilled. - Line 8: a promise’s
.then(callback)method registers a callback to run when the promise is fulfilled. LikesetTimeout, it returns at once. - Line 11 therefore prints before line 9.
Now a promise with a value. countGuests returns a Promise<number> that fulfills with 24 after 300 ms. Watch what the promise itself looks like before and after:
function countGuests(): Promise<number> {
return new Promise((resolve) => {
setTimeout(() => {
resolve(24);
}, 300);
});
}
const guests = countGuests();
console.log(guests);
guests.then((count) => {
console.log(`${count} guests are coming`);
console.log(guests);
});Promise { <pending> }
24 guests are coming
Promise { 24 }
Line 10 prints the promise, not a number: at that moment it is still pending. In line 11, .then hands its callback the fulfilled value, and the checker types count as number because it knows guests is a Promise<number>. By line 13 the same promise has settled, and Node shows the value inside it.
Key idea
A Promise<T> stands for a value of type T that will arrive later. It starts pending, then settles once: fulfilled
with a value, or rejected with an error. The value is never available on the line that gets the promise.
Watch out
Treating a promise as its value. A promise of a number is not a number, and the checker keeps them apart:
function countGuests(): Promise<number> {
return new Promise((resolve) => {
setTimeout(() => {
resolve(24);
}, 300);
});
}
const guests: number = countGuests();
console.log(guests + 1);promise-as-number.ts:9:7 - error TS2322: Type 'Promise<number>' is not assignable to type 'number'.TS2322 is the “wrong type” message from Day 1, here pointing at guests on line 9. The checker is right: when line 9 runs, there is no number yet, only a pending promise. Without the annotation, guests + 1 would be rejected instead. Get the value with .then, or with await from the next subsection. Fix or delete this file before your next check.
Pause and try
Question 4 · Tracing
Predict exactly what this program prints.
function getScore(): Promise<number> {
return new Promise((resolve) => {
setTimeout(() => {
resolve(87);
}, 100);
});
}
console.log("1");
getScore().then((score) => {
console.log(`2: ${score}`);
});
console.log("3");Check your reasoning
1
3
2: 87Line 9 prints 1. Line 10 calls getScore, which starts a 100 ms timer and returns a pending promise; .then registers the callback and returns at once. Line 13 prints 3. When the timer runs out, resolve(87) fulfills the promise, and the callback prints 2: 87.
Reread 17.3 Promises: Values That Arrive Later if your order differed.
Question 5 · Multiple choice
A function is declared function loadName(): Promise<string>. Which statement is true?
loadName()returns a string once the work is finishedloadName()returns a promise at once, which will later hold a string or an errorloadName()pauses the whole program until the string is readyloadName()returns a promise that can change from one string to another
Check your reasoning
B. A function with a Promise<string> return type gives back the promise straight away, while it is still pending. It later settles once: fulfilled with a string, or rejected with an error.
- A is wrong: the return value is the promise, never the string itself. That is the mistake TS2322 catches.
- C is wrong: nothing in JavaScript pauses the whole program; other code and timers keep running.
- D is wrong: a promise settles exactly once and never changes afterward.
Reread 17.3 Promises: Values That Arrive Later if you chose differently.
17.4 async Functions and await
.then works, but chaining several steps with it still means callbacks. JavaScript has a better way to wait for a promise, one that lets asynchronous code read like the synchronous code you have written since Day 1.
Two keywords work together:
async, written beforefunction, marks an async function: a function that may wait for promises inside it. An async function always returns a promise. If its body returns astring, the caller gets aPromise<string>.await, written before a promise, pauses this function until the promise settles, then gives back the fulfilled value.await delay(500)waits half a second;await countGuests()waits and then is the number 24.
The key word is “this function.” await does not freeze the program. The async function steps aside, the event loop runs other code and timers, and when the promise settles, the function carries on from the line after the await.
Worked example: Making tea without standing still
function delay(ms: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
async function makeTea(): Promise<string> {
console.log("Kettle on");
await delay(500);
console.log("Kettle boiled");
return "green tea";
}
console.log("Start");
const teaPromise = makeTea();
console.log("Reading while the kettle boils");
const drink = await teaPromise;
console.log(`Drinking ${drink}`);Start
Kettle on
Reading while the kettle boils
Kettle boiled
Drinking green teaFollow the run step by step:
| Step | Running | What happens | Prints |
|---|---|---|---|
| 1 | Line 14 | The file starts | Start |
| 2 | Line 15 → 8 | makeTea() runs its body synchronously up to its first await |
Kettle on |
| 3 | Line 9 | await delay(500) pauses makeTea; the call on line 15 gets a pending Promise<string> |
|
| 4 | Line 16 | The file carries on | Reading while the kettle boils |
| 5 | Line 17 | await teaPromise pauses the file itself until the tea is ready |
|
| 6 | Lines 10–11 | After 500 ms, makeTea resumes; return "green tea" fulfills its promise |
Kettle boiled |
| 7 | Lines 17–18 | The file resumes; drink is the string "green tea" |
Drinking green tea |
Two details matter. In step 2, an async function starts running straight away and only steps aside at its first await. And in step 7, drink has type string, not Promise<string>: await unwraps the promise. Hover over drink in VS Code to see it.
Line 7’s return type is Promise<string> even though line 11 returns a plain string. That is the rule for every async function: the return value is wrapped in a promise. This short program shows the wrapping directly:
async function getGreeting(): Promise<string> {
return "Hello";
}
const promise = getGreeting();
console.log(promise);
const greeting = await promise;
console.log(greeting);Promise { 'Hello' }
Hello
getGreeting never waits for anything, but because it is async, line 5 still gets a promise (already fulfilled, so Node shows the value inside). Line 7 unwraps it with await. The checker enforces the rule in the annotation too:
async function getGreeting(): string {
return "Hello";
}
console.log(await getGreeting());async-return-type.ts:1:31 - error TS1064: The return type of an async function or method must be the global Promise<T> type. Did you mean to write 'Promise<string>'?
TS1064 even suggests the fix: write Promise<string>, the type of what callers really get. Fix or delete this file before you go on.
Key idea
An async function always returns a promise: returning a T gives callers a Promise<T>. Inside it, await promise pauses only that function until the promise settles, then gives back the plain value.
Watch out
Forgetting await. Calling an async function without await gives you the promise, not the value:
type User = { name: string; age: number };
async function loadUser(): Promise<User> {
return { name: "Ana", age: 16 };
}
const user = loadUser();
console.log(user.name);forgot-await.ts:8:18 - error TS2339: Property 'name' does not exist on type 'Promise<User>'.user is a Promise<User>, and promises have no name property. In the terminal, under the code line, the checker adds a hint: Did you forget to use 'await'?. Add it:
type User = { name: string; age: number };
async function loadUser(): Promise<User> {
return { name: "Ana", age: 16 };
}
const user = await loadUser();
console.log(user.name);AnaThe checker cannot always catch a missing await. If you only print the result, console.log(loadUser()) type-checks fine and prints Promise { … } instead of the data. When you see Promise { in your output, look for a missing await. Delete forgot-await.ts before your next check.
Pause and try
Question 6 · Tracing
Predict exactly what this program prints, and the type of result.
function delay(ms: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
async function launch(): Promise<number> {
console.log("B");
await delay(100);
console.log("D");
return 3;
}
console.log("A");
const result = launch();
console.log("C");
console.log(await result);Check your reasoning
A
B
C
D
3Line 14 prints A. Line 15 calls launch, which runs synchronously up to its await: it prints B and then pauses, so result is a pending Promise<number>. Line 16 prints C. Line 17’s await result waits; after 100 ms, launch resumes, prints D, and returns 3, which fulfills the promise. await hands back the 3, and line 17 prints it.
Reread 17.4 async Functions and await if your order differed.
Question 7 · Multiple choice
What type does the checker give getAge in async function getAge() { return 16; }?
() => number() => Promise<number>() => Promise<void>() => Promise<Promise<number>>
Check your reasoning
B. The body returns a number, and an async function always wraps what it returns in a promise, so the inferred return type is Promise<number>.
- A is wrong: an async function never returns a plain value, even when it waits for nothing.
- C is wrong:
voidwould mean the function returns nothing, but it returns 16. - D is wrong: the value is wrapped once, not twice. Even returning a promise from an async function gives one layer, not two.
Reread 17.4 async Functions and await if you chose differently.
17.5 Top-Level await in Modules
Most of today’s examples use await outside any function, right in the file. await written at the top level of a file, not inside a function, is called top-level await. It is allowed only in a module, a file that JavaScript treats as part of a module system. On Day 13 you added "type": "module" to package.json, and that line is what makes every .ts file in the folder a module. Without it, the checker refuses await at the top level.
Top-level await is the easiest way to write a script whose steps happen one after another with pauses in between:
function delay(ms: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
console.log("Ready");
await delay(300);
console.log("Set");
await delay(300);
console.log("Go!");Ready
Set
Go!
The file pauses at line 8 for 300 ms, prints Set, pauses again at line 10, and prints Go!. While a top-level await waits, the rest of the file waits with it, but timers and other async work keep running.
The rule for await has exactly two places where it is allowed: inside an async function, and at the top level of a module. Inside an ordinary function, it is a type error:
function delay(ms: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
function countdown(): void {
console.log("Ready");
await delay(300);
console.log("Go!");
}
countdown();await-in-plain-function.ts:9:3 - error TS1308: 'await' expressions are only allowed within async functions and at the top levels of modules.
countdown is a plain function, so line 9 cannot pause it. A plain function always runs from start to finish in one go; only an async function can step aside and come back. Fix or delete this file before you go on.
Key idea
await is allowed in exactly two places: inside an async function and at the top level of a module. With "type": "module" in package.json, every file in the project is a module.
Pause and try
Question 8 · Debugging
Fix await-in-plain-function.ts in two different ways, and say what each fix changes about how countdown is called.
Check your reasoning
Fix 1: make countdown async. Line 7 becomes async function countdown(): Promise<void> {, so the await on line 9 is inside an async function. The call on line 13 becomes await countdown();, so the file waits until the countdown has finished; without that await, anything after line 13 would run straight away, before Go!.
function delay(ms: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
async function countdown(): Promise<void> {
console.log("Ready");
await delay(300);
console.log("Go!");
}
await countdown();Ready
Go!Fix 2: no function at all. Delete the function and write its three lines at the top level of the file, as in top-level.ts. Top-level await is allowed because the file is a module, and the output is the same.
TS1308 happened because await was in a plain function, one of the places where pausing is impossible.
Reread 17.5 Top-Level await in Modules if your fix differed.
17.6 Catching Errors Around await
Slow work is also the work most likely to fail: a file is missing, a server is down, a name is not found. On Day 16 you used throw to report a failure and try/catch to handle one. Async code uses the same tools.
There are two ways for a promise to be rejected:
- An async function
throws. Its promise becomes rejected with the thrown error. - Code inside
new Promise(...)callsreject(error), the second function it receives.
And await connects the two worlds: awaiting a rejected promise throws its error, right at the await, as if the line itself had said throw. First, here is what happens when nobody catches it:
function delay(ms: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
const ages = new Map([
["Ana", 16],
["Ben", 17],
]);
async function findAge(name: string): Promise<number> {
await delay(200);
const age = ages.get(name);
if (age === undefined) {
throw new Error(`No student named ${name}`);
}
return age;
}
console.log(await findAge("Ana"));
console.log(await findAge("Zoe"));
console.log("Done");16
Then Node stops with:
Error: No student named Zoe
Line 21 waits for Ana’s age and prints 16. Line 22 waits for Zoe’s, but findAge throws on line 16, its promise is rejected, and the await on line 22 throws the error. Nothing catches it, so the program crashes with a runtime error (the type checker had no complaint), and Done never prints.
Worked example: try and catch around await
Put the await inside try, exactly as Day 16 did with ordinary function calls:
function delay(ms: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
const ages = new Map([
["Ana", 16],
["Ben", 17],
]);
async function findAge(name: string): Promise<number> {
await delay(200);
const age = ages.get(name);
if (age === undefined) {
throw new Error(`No student named ${name}`);
}
return age;
}
for (const name of ["Ana", "Zoe", "Ben"]) {
try {
const age = await findAge(name);
console.log(`${name} is ${age}`);
} catch (error) {
if (error instanceof Error) {
console.log(`Lookup failed: ${error.message}`);
}
} finally {
console.log(`Finished ${name}`);
}
}Ana is 16
Finished Ana
Lookup failed: No student named Zoe
Finished Zoe
Ben is 17
Finished Benname |
Line 23 | Runs next | finally |
|---|---|---|---|
| Ana | fulfilled with 16 | line 24 | yes |
| Zoe | rejected, so the await throws | catch, lines 26–27 | yes |
| Ben | fulfilled with 17 | line 24 | yes |
- Line 23: when the promise is rejected, the
awaitthrows, so line 24 is skipped andcatchruns. - Line 25: the caught
errorhas typeunknown, as on Day 16: anything can be thrown, and the checker cannot know what. Line 26 narrows it withinstanceof Errorbefore readingmessage. - Line 29:
finallyruns whether the lookup worked or not. - The loop carries on after a failure, so Ben is still looked up. One bad name no longer ends the program.
The second way to reject is reject. Here a ticket checker answers after 200 ms, accepting codes that start with VIP:
function checkTicket(code: string): Promise<string> {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (code.startsWith("VIP")) {
resolve("front row");
} else {
reject(new Error(`Ticket ${code} is not valid`));
}
}, 200);
});
}
for (const code of ["VIP-7", "XX-1"]) {
try {
const seat = await checkTicket(code);
console.log(`${code}: ${seat}`);
} catch (error) {
console.log(error instanceof Error ? error.message : "Unknown problem");
}
}VIP-7: front row
Ticket XX-1 is not valid
Line 2 now receives both resolve and reject. Line 7 rejects the promise with an Error, and the await on line 15 throws it, so catch prints its message. Always reject with an Error object, as you would throw one, so that instanceof Error and message work in every catch.
Key idea
Awaiting a rejected promise throws its error at the await. Wrap the await in try/catch to handle it; the
caught value is unknown, so narrow it with instanceof Error before reading its message.
Watch out
A try without await catches nothing. This program calls findAge inside try, expecting catch to handle the failure:
function delay(ms: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
async function findAge(name: string): Promise<number> {
await delay(200);
throw new Error(`No student named ${name}`);
}
try {
findAge("Zoe");
console.log("Lookup started");
} catch (error) {
console.log("Caught it");
}
console.log("After the try");Lookup started
After the tryThen Node stops with:
Error: No student named Zoenpx tsc accepts it, and Caught it never prints. Without await, line 13 only starts the lookup and gets a pending promise; the try block finishes at once, and so does the file. 200 ms later the promise is rejected, but by then the try is long gone. A rejected promise that nobody awaits or catches crashes Node with its error. Add await on line 13:
function delay(ms: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
async function findAge(name: string): Promise<number> {
await delay(200);
throw new Error(`No student named ${name}`);
}
try {
await findAge("Zoe");
console.log("Lookup started");
} catch (error) {
console.log("Caught it");
}
console.log("After the try");Caught it
After the tryNow the try block waits for the lookup, so the rejection throws inside it.
Pause and try
Question 9 · Tracing
Predict exactly what this program prints.
async function openLocker(code: number): Promise<string> {
if (code !== 1234) {
throw new Error("Wrong code");
}
return "Locker open";
}
try {
console.log("Trying 1111");
console.log(await openLocker(1111));
console.log("Got in");
} catch (error) {
if (error instanceof Error) {
console.log(`Failed: ${error.message}`);
}
} finally {
console.log("Walking away");
}Check your reasoning
Trying 1111
Failed: Wrong code
Walking awayLine 9 prints Trying 1111. openLocker(1111) throws, so its promise is rejected, and the await on line 10 throws: line 10 prints nothing, and line 11 is skipped. catch narrows the error and prints its message. finally runs last, as it always does.
Reread 17.6 Catching Errors Around await if any line differed.
Question 10 · Multiple choice
Inside catch (error) after an await, why must you narrow error before reading error.message?
- Because a rejected promise’s error is always a string
- Because
errorhas typeunknown: a promise can be rejected with any value, so the checker cannot promise it is anError - Because
errorhas typePromise<Error>and needs its ownawait - You do not need to; after
await,errorhas typeError
Check your reasoning
B. Code can throw or reject with any value at all, so the checker types every caught value as unknown, just as on Day 16. instanceof Error narrows it to Error, and then message is allowed.
- A is wrong: the error is whatever was thrown or passed to
reject, usually anErrorobject. - C is wrong:
awaitalready unwrapped the rejection into a thrown value; there is no second promise. - D is wrong:
awaitdoes not change the rule. Readingerror.messagewithout narrowing is a type error.
Reread 17.6 Catching Errors Around await if you chose differently.
17.7 Running Work Together with Promise.all
await makes each step wait for the one before it. That is exactly right when a step needs the previous result, but wasteful when the steps have nothing to do with each other. Here three library shelves are loaded one after another, taking 300, 100, and 200 ms:
function delay(ms: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
async function loadShelf(
name: string,
ms: number,
books: number,
): Promise<number> {
console.log(`Start ${name}`);
await delay(ms);
console.log(`Finish ${name}`);
return books;
}
const fiction = await loadShelf("fiction", 300, 40);
const science = await loadShelf("science", 100, 25);
const history = await loadShelf("history", 200, 31);
console.log(`Total: ${fiction + science + history} books`);Start fiction
Finish fiction
Start science
Finish science
Start history
Finish history
Total: 96 books
Each shelf starts only after the last one has finished, so the program waits about 300 + 100 + 200 = 600 ms. But the three loads are independent. Like the three timers in 17.2, they could all wait at the same time.
Promise.all(promises) takes an array of promises and returns one promise that fulfills when all of them have fulfilled. Its value is an array of their values, in the same order as the array you passed, no matter which finished first. To run the jobs together, start them all first, without await, and then await the combined promise.
Worked example: Three shelves at once
function delay(ms: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
async function loadShelf(
name: string,
ms: number,
books: number,
): Promise<number> {
console.log(`Start ${name}`);
await delay(ms);
console.log(`Finish ${name}`);
return books;
}
const counts = await Promise.all([
loadShelf("fiction", 300, 40),
loadShelf("science", 100, 25),
loadShelf("history", 200, 31),
]);
console.log(counts);
const [fiction, science, history] = counts;
console.log(`Total: ${fiction + science + history} books`);Start fiction
Start science
Start history
Finish science
Finish history
Finish fiction
[ 40, 25, 31 ]
Total: 96 books- Lines 19 to 21 call
loadShelfthree times inside an array literal. Each call starts its shelf and returns a pending promise straight away, so all threeStartlines print together. - Line 18 hands the array of three promises to
Promise.alland awaits the result. - The shelves finish in the order of their delays: science (100 ms), history (200), fiction (300). The whole wait is about 300 ms, the longest single job, instead of 600.
countsis still[40, 25, 31], fiction first, becausePromise.allkeeps the order of the array it was given, not the order of finishing.- Line 24 unpacks the array with Day 6’s destructuring.
The checker follows the types through. Given promises of different types, Promise.all gives a tuple (Day 6) with each value’s own type in its own place:
async function getName(): Promise<string> {
return "Ana";
}
async function getScores(): Promise<number[]> {
return [88, 92, 79];
}
const [name, scores] = await Promise.all([getName(), getScores()]);
console.log(`${name.toUpperCase()}: best ${Math.max(...scores)}`);ANA: best 92
Promise.all receives a Promise<string> and a Promise<number[]>, so name is a string and scores is a number[], and line 10 can use toUpperCase and Math.max on them.
When one job fails. Promise.all is all or nothing. As soon as any one of its promises is rejected, the combined promise is rejected with that error, and the values of the others are lost:
function delay(ms: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
async function loadShelf(name: string, ms: number): Promise<number> {
await delay(ms);
if (name === "poetry") {
throw new Error("Shelf poetry is missing");
}
console.log(`Loaded ${name}`);
return 30;
}
try {
const counts = await Promise.all([
loadShelf("fiction", 300),
loadShelf("poetry", 100),
loadShelf("history", 200),
]);
console.log(counts);
} catch (error) {
if (error instanceof Error) {
console.log(`Promise.all failed: ${error.message}`);
}
}Promise.all failed: Shelf poetry is missing
Loaded history
Loaded fiction
Poetry fails first, at 100 ms, so the await on line 17 throws, and catch reports it. The other two shelves were already started, so they keep going and finish later, but their results go nowhere: line 22 never runs. And if two shelves had failed, you would hear only about the first.
To find out which jobs worked and which failed, make each job never reject. Wrap it in a function that catches its own error and returns a result union, the { ok: true; value: T } | { ok: false; error: string } shape from Day 16, as a generic type:
type Result<T> = { ok: true; value: T } | { ok: false; error: string };
function delay(ms: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
async function loadShelf(name: string, ms: number): Promise<number> {
await delay(ms);
if (name === "poetry") {
throw new Error("Shelf poetry is missing");
}
return 30;
}
async function tryLoadShelf(name: string, ms: number): Promise<Result<number>> {
try {
return { ok: true, value: await loadShelf(name, ms) };
} catch (error) {
return {
ok: false,
error: error instanceof Error ? error.message : "Unknown problem",
};
}
}
const names = ["fiction", "poetry", "history"];
const results = await Promise.all(
names.map((name, i) => tryLoadShelf(name, 100 * (i + 1))),
);
results.forEach((result, i) => {
if (result.ok) {
console.log(`${names[i]}: ${result.value} books`);
} else {
console.log(`${names[i]}: FAILED (${result.error})`);
}
});fiction: 30 books
poetry: FAILED (Shelf poetry is missing)
history: 30 books
tryLoadShelf on line 17 awaits the real load inside try. If it works, it returns { ok: true, value: … }; if it throws, catch returns { ok: false, error: … }. Either way its promise is fulfilled, so Promise.all always succeeds, and results is a Result<number>[]. Line 30 uses Day 11’s map to start one tryLoadShelf per name, with the index setting the delay. Lines 33 to 39 check ok to narrow each result, just like any discriminated union.
Key idea
Start independent jobs first, then await Promise.all([...]): they wait together, and the values come back in the
order you passed them. One rejection rejects the whole Promise.all; to report each failure, have each job catch its
own error and return a result union.
Pause and try
Question 11 · Multiple choice
Three independent async calls take 400, 100, and 250 ms. About how long does the program wait if it awaits them one after another, and if it awaits Promise.all of all three?
- One after another: 400 ms; with
Promise.all: 750 ms - One after another: 750 ms; with
Promise.all: 400 ms - One after another: 750 ms; with
Promise.all: 100 ms - Both about 750 ms, because JavaScript runs only one thing at a time
Check your reasoning
B. One after another, each wait starts when the previous one ends, so they add up: 400 + 100 + 250 = 750 ms. With Promise.all, all three wait at the same time, and the combined promise fulfills when the slowest has finished: about 400 ms.
- A swaps the two answers.
- C is wrong:
Promise.allwaits for all of the promises, not the first one. - D is wrong: one piece of code runs at a time, but waiting is not running. Timers, files, and network requests wait side by side.
Reread 17.7 Running Work Together with Promise.all if you chose differently.
Question 12 · Short answer
In all-results.ts, loadShelf("poetry", …) throws, yet await Promise.all(...) on line 29 never throws. Explain why, and say what would change if line 30 called loadShelf instead of tryLoadShelf.
Check your reasoning
Model answer: tryLoadShelf awaits loadShelf inside try, so the poetry error is caught there, and tryLoadShelf returns { ok: false, error: "Shelf poetry is missing" }. Its promise is fulfilled with that object, not rejected. Promise.all only rejects when one of its promises is rejected, and none is. If line 30 called loadShelf directly, the poetry promise would be rejected, so the await on line 29 would throw “Shelf poetry is missing”; with no try around it, the program would crash, and the fiction and history results would be lost.
A complete answer says the error is caught inside tryLoadShelf and turned into a fulfilled result, and that without it the rejection would make Promise.all reject.
Reread 17.7 Running Work Together with Promise.all if your explanation differed.
17.8 fetch and Reading JSON
The slowest and most common asynchronous job of all is asking another computer for data over the internet. Programs do it with fetch(url), which sends a request to a web address and returns a Promise<Response>. A Response is the server’s answer: a status code saying how it went, and a body, the data itself, often JSON (the text format for data you met on Day 16).
A real request looks like this. It needs an internet connection and a server at that address, so it has no output to show here:
const response = await fetch('https://example.com/quotes.json');
console.log(response.status);
const data: unknown = await response.json();
Notice the two awaits. The first waits for the server to start answering; the second waits for the whole body to arrive and turns its JSON into a value. The parts of a Response you need are:
| Part | Type | Meaning |
|---|---|---|
response.status |
number |
The status code: 200 means OK; 404 means “not found”; 500 means the server failed |
response.ok |
boolean |
true when the status is in the 200s, meaning success |
response.json() |
a promise | Reads the body and parses it as JSON, like JSON.parse; rejects if the body is not JSON |
response.text() |
Promise<string> |
Reads the body as plain text |
A 404 or a 500 does not reject the promise from fetch: the server did answer, just not with what you wanted. fetch rejects only when no answer arrives at all, for example when you are offline. So always check response.ok yourself.
To practice without a network, you can make a Response in code. new Response(text) builds the same kind of object fetch gives back, with status 200; new Response(text, { status: 404 }) builds a failure. Every verified example below uses one in place of a real server, and the code that reads it is exactly what you would write after a real fetch:
const body = JSON.stringify([
{
text: "Simplicity is prerequisite for reliability.",
author: "Edsger Dijkstra",
},
{
text: "The best way to predict the future is to invent it.",
author: "Alan Kay",
},
]);
const response = new Response(body);
console.log(response.ok, response.status);
const data: unknown = await response.json();
console.log(Array.isArray(data));
console.log(data);true 200
true
[
{
text: 'Simplicity is prerequisite for reliability.',
author: 'Edsger Dijkstra'
},
{
text: 'The best way to predict the future is to invent it.',
author: 'Alan Kay'
}
]
Line 1 turns an array into JSON text with JSON.stringify, and line 11 wraps it in a Response. Line 13 shows ok and status. Line 14 awaits json(), which parses the body back into an array of objects.
Line 14 also annotates data as unknown, and that is on purpose. The data came from outside the program: a server can send anything, and its owner can change it tomorrow. Day 16 taught that such data is unknown until a type guard has checked it. In a Node project, json() already returns Promise<unknown>; in the browser, which you start using tomorrow, it returns Promise<any>, and any would let you use the data unchecked. Writing : unknown yourself gives the same safety in both places.
Watch out
Using JSON data before checking it. In a Node project, json() gives unknown, so using the data straight away is a type error:
const response = new Response(JSON.stringify(["a", "b", "c"]));
const data = await response.json();
console.log(data.length);json-unknown.ts:3:13 - error TS18046: 'data' is of type 'unknown'.The checker will not let you read length of something it knows nothing about. Do not silence it with as string[]: Day 16 showed that as only tells the checker what to believe, and if the server sends something else, the program crashes later, far from the cause. Check the data with a type guard instead, as in the next example. Delete json-unknown.ts before your next check.
Worked example: Checking a response and its data
readQuotes turns a Response into a checked Quote[], or throws an error that says what went wrong. It is tried on three answers: a good one, a 404, and JSON of the wrong shape.
type Quote = { text: string; author: string };
function isQuote(value: unknown): value is Quote {
return (
typeof value === "object" &&
value !== null &&
"text" in value &&
typeof value.text === "string" &&
"author" in value &&
typeof value.author === "string"
);
}
function isQuoteArray(value: unknown): value is Quote[] {
return Array.isArray(value) && value.every(isQuote);
}
async function readQuotes(response: Response): Promise<Quote[]> {
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
const data: unknown = await response.json();
if (!isQuoteArray(data)) {
throw new Error("The data is not a list of quotes");
}
return data;
}
const responses = [
new Response(JSON.stringify([{ text: "Stay curious.", author: "Ana Lee" }])),
new Response("Not found", { status: 404 }),
new Response(JSON.stringify([{ text: "Missing an author" }])),
];
for (const response of responses) {
try {
const quotes = await readQuotes(response);
console.log(`"${quotes[0].text}" (${quotes[0].author})`);
} catch (error) {
console.log(error instanceof Error ? error.message : "Unknown problem");
}
}"Stay curious." (Ana Lee)
Request failed with status 404
The data is not a list of quotes- Lines 3 to 12: Day 16’s type guard. It returns
trueonly for an object with a stringtextand a stringauthor, and itsvalue is Quotereturn type tells the checker whattruemeans. - Lines 14 to 16: a second guard for a whole array: it must be an array, and
everyelement must passisQuote. - Line 19: first check the status. The 404 answer stops here, with its status in the message.
- Line 22: read the body as
unknown. - Line 23: then check the shape. The third answer has no
author, so the guard returnsfalse, and line 24 throws. - Line 26: after the guard, the checker knows
datais aQuote[], so the function can return it as one. - Lines 35 to 42: the caller awaits each answer in
tryand reports each failure, as in 17.6.
Files on your own computer. Node’s fetch reads only web addresses; it cannot open a file on your disk. For that, Node has an async twin of Day 13’s readFileSync: readFile from node:fs/promises, which returns a Promise<string> instead of making the program stand still while the disk is read. Put this books.json next to the program:
[
{ "title": "Dune", "pages": 412 },
{ "title": "Kim", "pages": 306 }
]
import { readFile } from "node:fs/promises";
type Book = { title: string; pages: number };
function isBook(value: unknown): value is Book {
return (
typeof value === "object" &&
value !== null &&
"title" in value &&
typeof value.title === "string" &&
"pages" in value &&
typeof value.pages === "number"
);
}
const text = await readFile("books.json", "utf8");
const data: unknown = JSON.parse(text);
if (Array.isArray(data) && data.every(isBook)) {
for (const book of data) {
console.log(`${book.title}: ${book.pages} pages`);
}
} else {
console.log("books.json is not a list of books");
}Dune: 412 pages
Kim: 306 pages
Line 16 awaits the file’s text, and line 17 parses it as unknown with Day 16’s JSON.parse. From there the steps are the same as after fetch: check with a guard, then use. Line 19 narrows data with Array.isArray and every(isBook) before line 21 reads title and pages. If books.json were missing, the promise from readFile would be rejected, and the await on line 16 would throw.
Key idea
await fetch(url) gives a Response; check response.ok, because a 404 does not reject. await response.json()
gives data from outside the program: store it as unknown and check it with a type guard before you use it. In Node,
readFile from node:fs/promises reads a file the same asynchronous way.
Pause and try
Question 13 · Multiple choice
A server is broken and answers every request with status 500 and an error page written in HTML. What happens when readQuotes from get-quotes.ts is given that response?
fetchrejects, soreadQuotesis never called- Line 19 sees
response.okisfalse, and line 20 throws “Request failed with status 500” - Line 22 rejects, because HTML is not valid JSON
- Line 23’s guard returns
false, and line 24 throws “The data is not a list of quotes”
Check your reasoning
B. A 500 is still an answer, so fetch fulfills with a Response whose ok is false and whose status is 500. readQuotes checks ok first and throws before it reads the body.
- A is wrong:
fetchrejects only when no answer arrives at all. A status code, even a bad one, is an answer. - C would be right if line 19 were missing:
json()rejects on a body that is not JSON. The status check prevents it. - D is wrong for the same reason: the code never gets past line 20.
Reread 17.8 fetch and Reading JSON if you chose differently.
Question 14 · Short answer
A classmate writes const quotes = (await response.json()) as Quote[]; and says it is shorter than a type guard and the checker is happy. Explain what can go wrong, and when.
Check your reasoning
Model answer: as does not check anything; it only tells the checker to treat the value as a Quote[]. If the server sends something else, such as an object, an error message, or quotes with a missing author, the program believes the wrong type and carries on. It then fails later, at runtime, wherever the missing data is used: for example quote.author.toUpperCase() stops with a TypeError, far from the line that caused it. A type guard checks the real data at the moment it arrives, so a bad answer is reported clearly, in one place, and the program can handle it.
A complete answer says that as performs no check, that bad data then causes a runtime error later, and that a type guard checks the data when it arrives.
Reread 17.8 fetch and Reading JSON if your explanation differed.
Putting it together
A library app asks a server for four shelves at once, checks every answer, and reports which shelves loaded and which failed, with the total number of pages it could load. Since there is no real server, fakeFetch stands in for fetch: it waits 100 ms and answers from a Map of addresses, with a 404 for any address it does not know. Everything below fakeFetch would work unchanged with the real fetch. Make sure npx tsc is clean in your day17 folder first: fix or delete any broken file from today.
type Book = { title: string; pages: number };
type Result<T> = { ok: true; value: T } | { ok: false; error: string };
function delay(ms: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
// A pretend web server: each address and the text it sends back.
const server = new Map([
[
"/shelves/fiction",
JSON.stringify([
{ title: "Dune", pages: 412 },
{ title: "Kim", pages: 306 },
]),
],
[
"/shelves/science",
JSON.stringify([
{ title: "Cosmos", pages: 365 },
{ title: "Silent Spring", pages: 378 },
]),
],
["/shelves/poetry", JSON.stringify([{ title: "Odes" }])],
]);
// Stands in for fetch: waits, then answers the way a web server would.
async function fakeFetch(url: string): Promise<Response> {
await delay(100);
const body = server.get(url);
if (body === undefined) {
return new Response("Not found", { status: 404 });
}
return new Response(body);
}
function isBook(value: unknown): value is Book {
return (
typeof value === "object" &&
value !== null &&
"title" in value &&
typeof value.title === "string" &&
"pages" in value &&
typeof value.pages === "number"
);
}
async function loadShelf(url: string): Promise<Book[]> {
const response = await fakeFetch(url);
if (!response.ok) {
throw new Error(`${url} answered ${response.status}`);
}
const data: unknown = await response.json();
if (!Array.isArray(data) || !data.every(isBook)) {
throw new Error(`${url} is not a list of books`);
}
return data;
}
async function tryLoadShelf(url: string): Promise<Result<Book[]>> {
try {
return { ok: true, value: await loadShelf(url) };
} catch (error) {
return {
ok: false,
error: error instanceof Error ? error.message : "Unknown problem",
};
}
}
const urls = [
"/shelves/fiction",
"/shelves/science",
"/shelves/poetry",
"/shelves/history",
];
console.log(`Loading ${urls.length} shelves...`);
const results = await Promise.all(urls.map(tryLoadShelf));
let totalPages = 0;
results.forEach((result, i) => {
if (result.ok) {
const pages = result.value.reduce((sum, book) => sum + book.pages, 0);
totalPages += pages;
console.log(
`OK ${urls[i]}: ${result.value.length} books, ${pages} pages`,
);
} else {
console.log(`FAILED ${result.error}`);
}
});
console.log(`Total pages loaded: ${totalPages}`);npx tsc reports no errors, and node library.ts shows:
Loading 4 shelves...
OK /shelves/fiction: 2 books, 718 pages
OK /shelves/science: 2 books, 743 pages
FAILED /shelves/poetry is not a list of books
FAILED /shelves/history answered 404
Total pages loaded: 1461
Follow one shelf at a time through the program:
| Lines | What happens | Idea |
|---|---|---|
| 4–8 | delay turns setTimeout into a Promise<void> |
17.3 |
| 30–37 | fakeFetch is async, so it returns a Promise<Response>, just like fetch |
17.4, 17.8 |
| 51 | loadShelf awaits the response |
17.4 |
| 52–54 | A 404 is not a rejection, so ok is checked; history fails here |
17.8 |
| 55–58 | The body is read as unknown and checked with the guard; poetry, with no pages, fails here |
17.8 |
| 62–71 | tryLoadShelf catches any error and returns a result union, so its promise never rejects |
17.6, 17.7 |
| 80 | map starts all four loads, and Promise.all waits for them together: about 100 ms, not 400 |
17.7 |
| 83–93 | Each result is narrowed on ok; the good ones are summed with reduce |
17.7 |
The top-level await on line 80 (17.5) is the only place the file itself waits. Try making fakeFetch wait url.length * 10 ms instead of 100: the shelves finish in a different order, but the report does not change, because Promise.all keeps the order of urls.
Common mistakes
| Message or symptom | Usual cause | Fix |
|---|---|---|
TS2322: Type 'Promise<number>' is not assignable to type 'number'. |
Using a promise as if it were its value | await it |
TS2339: Property 'name' does not exist on type 'Promise<User>'. |
A missing await |
await the call |
Promise { <pending> } in the output |
Printing a promise instead of its value | await it before printing |
TS1064: The return type of an async function … must be the global Promise<T> type. |
Annotating an async function with the plain type | Write Promise<string> |
TS1308: 'await' expressions are only allowed within async functions … |
await inside a plain function |
Mark the function async |
TS18046: 'data' is of type 'unknown'. |
Using JSON data before checking it | A type guard |
A variable still holds its old value after setTimeout |
Reading a result before the callback has run | Use it inside the callback, or await |
A crash even though the call is inside try |
The call in try has no await |
await it inside try |
A 404 page treated as data, or json() rejecting on HTML |
Not checking response.ok |
if (!response.ok) before json() |
| Independent jobs take the sum of their times | Awaiting them one after another | Promise.all |
Promise.all loses every result when one fails |
It rejects as soon as one job rejects | Each job returns a result union |
Vocabulary
| Term | Definition | Example |
|---|---|---|
| synchronous | Running one step after another, each finished before the next starts | console.log("A"); console.log("B"); |
| asynchronous | Started now and finished later, while the rest of the program carries on | setTimeout(callback, 1000) |
| millisecond | A thousandth of a second | 1000 ms is one second |
| event loop | The part of Node that runs your file, then each ready callback in turn, until nothing is left | Runs a timer’s callback when it is due |
| callback hell | Callbacks nested inside callbacks, one level deeper for every step | step(…, () => { step(…, () => { … }) }) |
| promise | An object that stands for a value that is not ready yet | delay(500) |
| pending | The state of a promise whose work is still going on | Promise { <pending> } |
| fulfilled | The state of a promise whose work succeeded; it holds a value | Promise { 24 } |
| rejected | The state of a promise whose work failed; it holds an error | reject(new Error("Not valid")) |
| settle | To leave the pending state, by being fulfilled or rejected, exactly once | resolve(24) |
| async function | A function marked async; it always returns a promise and may use await |
async function load(): Promise<string> |
| await | Pauses an async function (or module) until a promise settles, then gives back its value | const age = await findAge("Ana"); |
| top-level await | await written outside any function, allowed in a module |
await delay(300); at the top of a file |
| module | A file treated as part of a module system; "type": "module" makes every .ts file one |
Any file in a Day 13 project |
| Promise.all | Combines an array of promises into one that fulfills with all their values, in order | await Promise.all([a(), b()]) |
| fetch | Sends a request to a web address and returns a Promise<Response> |
await fetch(url) |
| Response | A server’s answer: a status code and a body | new Response(text, { status: 404 }) |
| status code | A number saying how a request went: 200 OK, 404 not found, 500 server failed | response.status |
| body | The data a response carries, read with json() or text() |
await response.json() |
Summary
- Asynchronous work starts now and finishes later. The event loop runs your file to its end first, then each ready callback, one at a time;
setTimeoutis the simplest example, and a value set in its callback is not there on the next line. - A promise (
Promise<T>) stands for a value that arrives later. It is pending until it settles once, fulfilled with a value or rejected with an error.new Promise((resolve, reject) => …)makes one, as indelay. - An async function always returns a promise.
awaitpauses that function, or the top level of a module, until the promise settles, then gives back the plain value; it is allowed nowhere else. - Awaiting a rejected promise throws, so put the
awaitinsidetry/catch, and narrow theunknownerror withinstanceof Error. Atrywithoutawaitcatches nothing. Promise.allruns independent jobs together and keeps their order; it rejects if any one job does, so have each job return a result union when you need to know which failed.fetchgives aResponse: checkok, because a 404 is not a rejection, then readjson()asunknownand check it with a type guard before using it.
Practice
Do these in your day17 folder. First make sure npx tsc prints nothing there: if any broken file from today is still in the folder (promise-as-number.ts, async-return-type.ts, forgot-await.ts, await-in-plain-function.ts, or json-unknown.ts), fix it or delete it. Then write each program yourself, check it with npx tsc, run it with node, and only then open the answer.
Question 15 · Short answer
Countdown. Write a delay(ms) function that returns a promise, and an async countdown(from: number) function that prints from, from - 1, …, 1, one per second, then Liftoff!. Call it with 3, and print Countdown finished only after the countdown has ended.
Check your reasoning
One possible solution:
function delay(ms: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
async function countdown(from: number): Promise<void> {
for (let n = from; n >= 1; n--) {
console.log(n);
await delay(1000);
}
console.log("Liftoff!");
}
await countdown(3);
console.log("Countdown finished");3
2
1
Liftoff!
Countdown finisheddelay is the function from 17.3. Inside countdown, Day 5’s for loop counts down, and await delay(1000) pauses the function for a second after each number, so the numbers appear one second apart. Because countdown is async, it returns a Promise<void>, and the top-level await on line 15 waits for that promise, so Countdown finished prints last. Remove that await and Countdown finished prints straight after 3.
Reread 17.4 async Functions and await and 17.5 Top-Level await in Modules if your result differed.
Question 16 · Short answer
Random quote. Make a quotes.json file holding an array of quotes, each with a text and an author. Write a program that loads it, checks that it really is a non-empty list of quotes, and prints one at random, with any failure reported as a message rather than a crash. Node’s fetch cannot open a file on your disk, so read it with readFile from node:fs/promises (17.8); everything after that is the same as after fetch.
To pick at random, use Math.random(), which gives a different number from 0 up to (but not including) 1 each time it is called: Math.floor(Math.random() * quotes.length) is a random index. Random output is hard to test, so also let the program take a quote number from the command line (Day 13’s process.argv) and print that quote instead.
Check your reasoning
One possible solution, with this quotes.json:
[
{
"text": "Simplicity is prerequisite for reliability.",
"author": "Edsger Dijkstra"
},
{
"text": "The most dangerous phrase in the language is: we've always done it this way.",
"author": "Grace Hopper"
},
{
"text": "The best way to predict the future is to invent it.",
"author": "Alan Kay"
}
]import { readFile } from "node:fs/promises";
type Quote = { text: string; author: string };
function isQuote(value: unknown): value is Quote {
return (
typeof value === "object" &&
value !== null &&
"text" in value &&
typeof value.text === "string" &&
"author" in value &&
typeof value.author === "string"
);
}
async function loadQuotes(file: string): Promise<Quote[]> {
const text = await readFile(file, "utf8");
const data: unknown = JSON.parse(text);
if (!Array.isArray(data) || !data.every(isQuote) || data.length === 0) {
throw new Error(`${file} does not hold a list of quotes`);
}
return data;
}
try {
const quotes = await loadQuotes("quotes.json");
const picked = process.argv[2];
const index =
picked === undefined
? Math.floor(Math.random() * quotes.length)
: Number(picked) - 1;
const quote = quotes[index];
if (quote === undefined) {
console.log(`There is no quote number ${picked}`);
} else {
console.log(`Quote ${index + 1} of ${quotes.length}:`);
console.log(`"${quote.text}" (${quote.author})`);
}
} catch (error) {
console.log(error instanceof Error ? error.message : "Unknown problem");
}node random-quote.ts prints a different quote from run to run. node random-quote.ts 2 always prints:
Quote 2 of 3:
"The most dangerous phrase in the language is: we've always done it this way." (Grace Hopper)loadQuotes awaits the file’s text, parses it as unknown, and throws unless the type guard passes for every element and the list is not empty. The top-level code awaits it inside try, so a missing or broken file prints a message instead of crashing. Line 27 reads the optional argument; with none, line 30 picks a random index, and with one, line 31 turns the 1-based number into a 0-based index. An index past the end gives undefined at runtime (Day 6), even though the checker types quote as a Quote, so line 33 checks for it: try node random-quote.ts 9. Then rename quotes.json and run it again.
Reread 17.8 fetch and Reading JSON and 17.6 Catching Errors Around await if your result differed.
Question 17 · Short answer
Three files at once. Make two team files: red.json, an array of names, and blue.json, which holds something that is not an array of names. Do not make a green.json. Load all three files together with Promise.all, then print each team that loaded and, for each one that failed, its file name and the reason. End with how many loaded and how many failed.
Check your reasoning
One possible solution, with these two files:
red.json:
["Ana", "Ben", "Chen"]blue.json:
{ "captain": "Mo" }import { readFile } from "node:fs/promises";
type Result<T> = { ok: true; value: T } | { ok: false; error: string };
function isStringArray(value: unknown): value is string[] {
return (
Array.isArray(value) && value.every((item) => typeof item === "string")
);
}
async function loadTeam(file: string): Promise<Result<string[]>> {
try {
const text = await readFile(file, "utf8");
const data: unknown = JSON.parse(text);
if (!isStringArray(data)) {
return { ok: false, error: "not a list of names" };
}
return { ok: true, value: data };
} catch (error) {
return {
ok: false,
error: error instanceof Error ? error.message : "Unknown problem",
};
}
}
const files = ["red.json", "blue.json", "green.json"];
const results = await Promise.all(files.map(loadTeam));
let failed = 0;
results.forEach((result, i) => {
if (result.ok) {
console.log(`${files[i]}: ${result.value.join(", ")}`);
} else {
failed++;
console.log(`${files[i]} failed: ${result.error}`);
}
});
console.log(`${files.length - failed} loaded, ${failed} failed`);red.json: Ana, Ben, Chen
blue.json failed: not a list of names
green.json failed: ENOENT: no such file or directory, open 'green.json'
1 loaded, 2 failedloadTeam never rejects: a file that is not a list of names returns a failure from line 16, and a file that cannot be read (or is not JSON at all) throws inside try, and line 22 turns the error’s message into a failure. ENOENT is Node’s code for “no such file.” Because every promise fulfills, Promise.all on line 28 always gives all three results, in the order of files, and the loop narrows each one on ok. If loadTeam let its errors escape, Promise.all would reject at the first failure, and you would never learn about the other one.
Reread 17.7 Running Work Together with Promise.all if your result differed.
Review questions
Question 18 · Tracing
Predict exactly what this program prints. It mixes a timer with two async calls.
function delay(ms: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
async function bake(item: string, ms: number): Promise<string> {
console.log(`Oven: ${item}`);
await delay(ms);
return `${item} done`;
}
setTimeout(() => {
console.log("Timer: 150 ms");
}, 150);
const cake = bake("cake", 300);
const bread = bake("bread", 100);
console.log(await bread);
console.log(await cake);Check your reasoning
Oven: cake
Oven: bread
bread done
Timer: 150 ms
cake done| Time | What happens | Prints |
|---|---|---|
| 0 ms | Line 13 sets a 150 ms timer | |
| 0 ms | Line 16: bake("cake", 300) runs up to its await |
Oven: cake |
| 0 ms | Line 17: bake("bread", 100) runs up to its await; both bakes now wait together |
Oven: bread |
| 0 ms | Line 18: the file awaits bread |
|
| 100 ms | Bread’s delay ends; its promise fulfills with "bread done"; line 18 prints it |
bread done |
| 100 ms | Line 19: the file awaits cake |
|
| 150 ms | The timer runs while the file waits | Timer: 150 ms |
| 300 ms | Cake’s delay ends; line 19 prints its value | cake done |
The timer prints between the two results because waiting at line 19 does not block the event loop.
Reread 17.4 async Functions and await and 17.1 Why Some Work Waits if your order differed.
Question 19 · Debugging
This program should add up two vote counts. Find the error, explain it, and fix it so both counts are fetched together.
async function countRed(): Promise<number> {
return 12;
}
async function countBlue(): Promise<number> {
return 9;
}
const total = countRed() + countBlue();
console.log(`Total votes: ${total}`);Check your reasoning
add-promises.ts:9:15 - error TS2365: Operator '+' cannot be applied to types 'Promise<number>' and 'Promise<number>'.Both functions are async, so each call returns a Promise<number>, not a number, and + cannot add two promises. The type checker stops the program before it runs. The fix awaits both, together:
async function countRed(): Promise<number> {
return 12;
}
async function countBlue(): Promise<number> {
return 9;
}
const [red, blue] = await Promise.all([countRed(), countBlue()]);
console.log(`Total votes: ${red + blue}`);Total votes: 21Promise.all starts both counts and gives back a [number, number] tuple, which destructuring unpacks. (await countRed()) + (await countBlue()) would also be correct, but it would wait for the counts one after another.
Reread 17.4 async Functions and await and 17.7 Running Work Together with Promise.all if your fix differed.
Question 20 · Short answer
A program needs to load a user by name, then load that user’s orders using the user’s id, and also load today’s prices, which do not depend on the user. Which of these three jobs can go in one Promise.all, and which must wait for another? Sketch the await lines.
Check your reasoning
Model answer: The orders need the user’s id, so they cannot start until the user has loaded: those two must run one after the other. The prices are independent, so they can load at the same time as the user (or as the whole user-then-orders chain). One good shape:
const [user, prices] = await Promise.all([loadUser("Ana"), loadPrices()]);
const orders = await loadOrders(user.id);A complete answer says that a job which needs another job’s result must wait for it, that independent jobs can share a Promise.all, and puts loadOrders after the user is known.
Reread 17.7 Running Work Together with Promise.all if your plan differed.
Question 21 · Multiple choice
await Promise.all([a(), b(), c()]) is inside try. The promise from b() is rejected after 50 ms; a() and c() would fulfill after 200 ms. What happens?
- After 200 ms, the
awaitgives[valueA, undefined, valueC] - After 50 ms, the
awaitthrowsb’s error, andcatchruns;a()andc()keep running, but their values are lost - After 50 ms, the
awaitthrows, anda()andc()are stopped - After 200 ms, the
awaitthrows all the errors together
Check your reasoning
B. Promise.all rejects as soon as one of its promises rejects, with that promise’s error, so the await throws after 50 ms. Nothing stops the other two jobs; they finish later, but no one is waiting for their values.
- A is wrong:
Promise.allnever fills in a failed slot. That kind of report needs each job to catch its own error. - C is wrong: a promise cannot be cancelled by
Promise.all;all-fails.tsshowed the other shelves still loading. - D is wrong: it does not wait for the rest, and it reports only the first error.
Reread 17.7 Running Work Together with Promise.all if you chose differently.
Question 22 · Tracing
readQuotes from get-quotes.ts is given new Response(JSON.stringify({ text: "Hi", author: "Mo" })). Which line throws, and what message does the caller print? Explain each check the response passes or fails.
Check your reasoning
The data is not a list of quotes- Line 19: the response was built with no status, so it is 200, and
okistrue. The status check passes. - Line 22: the body is valid JSON, so
json()fulfills with an object. - Line 23:
isQuoteArrayreturnsfalse, becauseArray.isArrayisfalsefor a single object, even though the object itself would passisQuote. - Line 24 throws, and the caller’s
catchprints the message.
The shape check is what catches “one quote instead of a list,” something no status code would reveal.
Reread 17.8 fetch and Reading JSON if your answer differed.
Question 23 · Short answer
Rewrite nested-callbacks.ts from 17.2 without nesting, using delay and await, so that it prints the same four lines in the same order. Then say in one sentence why the new version is easier to extend with a fourth step.
Check your reasoning
Model answer:
function delay(ms: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
async function step(name: string, ms: number): Promise<void> {
await delay(ms);
console.log(name);
}
await step("Boil the water", 300);
await step("Steep the tea", 200);
await step("Add milk", 100);
console.log("Tea is ready");Boil the water
Steep the tea
Add milk
Tea is readystep now returns a promise instead of taking a callback, and each await finishes one step before the next starts, so the order is the same. A fourth step is one more await line at the same indentation, instead of another callback nested one level deeper, and a try around the lines would catch a failure at any step.
A complete answer makes step return a promise (async, or using delay), awaits the steps in order at the same level, and names the flat shape as the advantage.
Reread 17.4 async Functions and await and 17.2 Callbacks That Run Later if your version differed.
Go further
MDN’s guide explains promises in more depth, including .then chains, .catch, and Promise.allSettled, a built-in way to wait for every job and learn which failed: MDN: Using promises. For requests, see MDN: Using the Fetch API, and for how TypeScript writes the return type of an async function, the note on functions that return promises in TypeScript Handbook: Everyday Types.
Reflection
Check each statement. If the answer is “not yet,” reread the linked subsection.
- I can explain why a setTimeout callback runs after the rest of the file, and predict the order a program prints in. Reread
- I can pass a callback to run later, and say why a value set inside it is not there on the next line. Reread
- I can write a function that returns a Promise, such as delay, and name the three states of a promise. Reread
- I can write an async function, await its result, and read the message when I forget the await. Reread
- I can say where await is allowed, and use it at the top level of a module. Reread
- I can catch a rejected promise with try and catch around await, and narrow the unknown error. Reread
- I can run independent jobs together with Promise.all and report which ones failed. Reread
- I can check a Response and validate its JSON with a type guard before using it. Reread