Learn the third state of a promise, rejected, and what await does when the wait goes wrong: it throws the reason on its own line. Make a promise that is rejected, catch its error with try and catch around await, see that a throw in an async function rejects its promise, and find out why a try without await catches nothing.
TypeScript
Fundamentals
Errors in async code: `try` around `await`. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
In the last two lessons every coffee arrived: the buzzer went, and
await handed you the drink. Real waits do not always end that way.
The café runs out of milk, a website does not answer, a file is not
where you said. In lesson 8.3 a function refused a bad value with
throw, and a try / catch caught the refusal. A wait can fail
too, only later, after the line that started it has already run.
In this lesson your promises fail, and your program does not stop
because of it. You make a promise that is rejected, catch its error
with a try around await, see that a throw in an async function
fails the same way, and find out why a try that does not wait
catches nothing.
Rejected: when the wait goes wrong
Lesson 11.3 named a promise's three states, and so far you have met
two: pending, and fulfilled with a value. The third is rejected:
the wait is over, and it went wrong. A rejected promise holds no
value. It holds the reason, usually an Error that says what
went wrong. Like a fulfilled promise, a rejected one never changes
state again.
The function you give new Promise gets a second tool besides
resolve. reject ends the wait the other way: call it, and the
promise is rejected with what you hand it. Here is brew from the
last lesson, now with the drink's name as a parameter. A latte needs
milk, and the café
has none. Make serve.ts in ~/projects/taskkit:
serve.tsts
function brew(drink: string): Promise<string> { return new Promise((resolve, reject) => { setTimeout(() => { if (drink === "Latte") { reject(new Error("Out of milk")); } else { resolve(drink); } }, 1000); });}async function serve(drink: string): Promise<void> { const ready = await brew(drink); console.log("Ready:", ready);}serve("Latte");console.log("Order taken");
A second later the timer calls reject on line 5, and the promise is
rejected. await on line 13 cannot hand serve a drink, so it does
the only thing left: it throws the reason on its own line, as if
throw new Error("Out of milk") stood there. Line 14 never runs.
Nothing catches the error, so Node stops, as it did for an uncaught
throw in lesson 8.3. Run it:
bash
node serve.ts
What Node printstext
Order takenfile:///Users/ana/projects/taskkit/serve.ts:5 reject(new Error("Out of milk")); ^Error: Out of milk
Order takenfile:///C:/Users/ana/projects/taskkit/serve.ts:5 reject(new Error("Out of milk")); ^Error: Out of milk
Order takenfile:///home/ana/projects/taskkit/serve.ts:5 reject(new Error("Out of milk")); ^Error: Out of milk
After those lines come the stack trace and Node.js v24.11.1. Order taken printed first: line 17 ran while serve waited. The ^ points
at line 5, where the error was made and handed to reject, not at line
13, where await threw it. When Node stops on a rejection, the line it
shows is where the error was made; from there, find the await that
waited for it.
Catching it: try around await
Because await throws the reason on its line, you catch it with what
you already have: the try / catch of lesson 8.3, put around the
await. In serve.ts, replace serve with this one:
serve.tsts
function brew(drink: string): Promise<string> { return new Promise((resolve, reject) => { setTimeout(() => { if (drink === "Latte") { reject(new Error("Out of milk")); } else { resolve(drink); } }, 1000); });}async function serve(drink: string): Promise<void> { try { const ready = await brew(drink); console.log("Ready:", ready); } catch (error) { if (error instanceof Error) { console.log("Sorry:", error.message); } }}serve("Latte");console.log("Order taken");
The catch checks with instanceof Error before it reads message,
as in lesson 8.3, and for the same reason. What lands in the catch
is whatever the promise was rejected with, and that can be anything:
reject("Out of milk") with a string is as legal as throw 7 was in
lesson 8.3. So TypeScript gives the error box the type unknown, and
you check it before you use it: with instanceof Error, or with
TaskKit's messageOf (lesson 8.5), which turns any caught value into
a sentence.
Pick a drink with the switch, press Next step to walk through it,
or let it play:
Callstack
Timer
Promise
Terminal
Call stack: serveserveserve
Call stack: awaitawaitawait
Timer: 1 second1second1second
Promise: pendingpendingpending
Call stack: line 23line23line23
Terminal: Order takenOrdertakenOrdertaken
Call stack: emptyemptyempty
Promise: fulfilledfulfilledfulfilled
Call stack: serve, line 15serve,line15serve,line15
Line 22 calls serve. Inside the try, line 14 calls brew.
serve waits for brew's promise. It pauses and leaves the
stack.
Node counts the second outside your code.
brew's promise: the drink is not made yet.
Back in the file, line 23 prints. The file is done.
Line 23's text is out while serve waits.
The stack is empty while the timer counts. serve is waiting,
off the stack. The timer's callback, which calls resolve or
reject, runs too briefly to draw.
The timer's callback calls resolve("Flat white").
The promise is fulfilled, so await gives ready the drink and
line 15 prints. The catch is skipped.
Line 15 prints. Nothing is left to wait for, so Node ends.
A rejected promise makes await throw, and the catch takes it
All 10 steps shown.Step 1 of 10: Call stack: serveStep 2 of 10: Call stack: awaitStep 3 of 10: Timer: 1 secondStep 4 of 10: Promise: pendingStep 5 of 10: Call stack: line 23Step 6 of 10: Terminal: Order takenStep 7 of 10: Call stack: emptyStep 8 of 10: Promise: fulfilledStep 9 of 10: Call stack: serve, line 15Step 10 of 10: Terminal: Ready: Flat white
All 10 steps shown.
Callstack
Timer
Promise
Terminal
Call stack: serveserveserve
Call stack: awaitawaitawait
Timer: 1 second1second1second
Promise: pendingpendingpending
Call stack: line 23line23line23
Terminal: Order takenOrdertakenOrdertaken
Call stack: emptyemptyempty
Promise: rejectedrejectedrejected
Call stack: serve, catchserve,catchserve,catch
Terminal: Sorry: Out of milkSorry:OutofmilkSorry:Outofmilk
Time
Line 22 calls serve. Inside the try, line 14 calls brew.
serve waits for brew's promise. It pauses and leaves the
stack.
Node counts the second outside your code.
brew's promise: the drink is not made yet.
Back in the file, line 23 prints. The file is done.
Line 23's text is out while serve waits.
The stack is empty while the timer counts. serve is waiting,
off the stack. The timer's callback, which calls resolve or
reject, runs too briefly to draw.
The timer's callback calls reject with an Error: out of milk.
The promise is rejected, so await throws its error on line 14.
Line 15 is skipped, and the catch prints the message.
Line 18 prints. Nothing is left to wait for, so Node ends.
A rejected promise makes await throw, and the catch takes it
All 10 steps shown.Step 1 of 10: Call stack: serveStep 2 of 10: Call stack: awaitStep 3 of 10: Timer: 1 secondStep 4 of 10: Promise: pendingStep 5 of 10: Call stack: line 23Step 6 of 10: Terminal: Order takenStep 7 of 10: Call stack: emptyStep 8 of 10: Promise: rejectedStep 9 of 10: Call stack: serve, catchStep 10 of 10: Terminal: Sorry: Out of milk
All 10 steps shown.
Check it with npm run check, the script npm (Node package manager)
runs for TaskKit, and run it:
bash
npm run checknode serve.ts
The check prints only its two > lines. Node prints Order taken at
once and, a second later, the catch's line instead of a stack
trace:
Outputtext
Order takenSorry: Out of milk
Change line 22 to serve("Flat white"); and run it again: Order taken, then Ready: Flat white, and the catch never runs.
throw in an async function
An async function can fail on its own, without a timer: it can
throw, as any function can since lesson 8.3. But an async
function always gives back a promise (lesson 11.4), so its throw
does not reach the line that called it. It rejects the function's
promise, with the thrown error as the reason. Whoever awaits that
promise gets the error thrown again, on the await line, and a try
there catches it:
ts
async function countTasks(titles: string[]): Promise<number> { if (titles.length === 0) { throw new Error("The list is empty"); } return titles.length;}async function report(titles: string[]): Promise<void> { try { const count = await countTasks(titles); console.log(`${count} tasks`); } catch (error) { if (error instanceof Error) { console.log("Not counted:", error.message); } }}report([]);
Press Run: it prints Not counted: The list is empty. The error
went from line 3 into countTasks's promise, and came back out at
line 9's await. So a failed wait travels up the same way an answer
does: through every await, until a catch takes it.
Predict the order
countTasks and report are the ones from above. This time report
is called twice, once with two tasks and once with none, and the file
prints a line of its own after the calls.
Predict
What is the second line this program prints?
ts
async function countTasks(titles: string[]): Promise<number> { if (titles.length === 0) { throw new Error("The list is empty"); } return titles.length;}async function report(titles: string[]): Promise<void> { try { const count = await countTasks(titles); console.log(`${count} tasks`); } catch (error) { if (error instanceof Error) { console.log("Not counted:", error.message); } }}report(["Buy milk", "Call Mom"]);report([]);console.log("Both asked");
The common mistake: a try that does not wait
A try catches what is thrown while its lines run. With a call that
gives back a promise, it is easy to put the try around the call and
forget the await.
Common mistake
A try around a call that is not awaited
Go back to the serve of the first section, the one with no try
inside, and put the call at the bottom of the file inside a try. Make
serve.ts read:
serve.tsts
function brew(drink: string): Promise<string> { return new Promise((resolve, reject) => { setTimeout(() => { if (drink === "Latte") { reject(new Error("Out of milk")); } else { resolve(drink); } }, 1000); });}async function serve(drink: string): Promise<void> { const ready = await brew(drink); console.log("Ready:", ready);}try { serve("Latte");} catch (error) { console.log("Sorry, no latte");}console.log("Order taken");
npm run check finds nothing wrong, and node serve.ts prints exactly
what it printed in the first section: Order taken, then the crash at
line 5 with Error: Out of milk, the stack trace and the Node.js
line, as if the try were not there.
The try and the error never meet. Follow when each part happens:
try
Promise
Terminal
try: serve()serve()serve()
Promise: pendingpendingpending
try: catch: skippedcatch:skippedcatch:skipped
Terminal: Order takenOrdertakenOrdertaken
Promise: rejectedrejectedrejected
Terminal: Error: Out of milkError:OutofmilkError:Outofmilk
Time
serve().
Line 17 calls serve, which gives back a pending promise at
once. Nothing threw, so the try is over.
pending.
brew's promise waits for the timer.
catch: skipped.
Nothing was thrown inside the try, so the catch never runs.
Order taken.
Line 21 prints. The file is done.
rejected.
Out of milk. await throws in serve, and nothing there
catches it.
Error: Out of milk.
Nobody catches the error, so Node prints it and stops.
The try is over a second before the promise is rejected
Error: Out of milk
The fix
Put the try where the error is thrown: around the await, inside
serve, as in the second section. The file then calls serve with no
try of its own.
serve.tsts
function brew(drink: string): Promise<string> { return new Promise((resolve, reject) => { setTimeout(() => { if (drink === "Latte") { reject(new Error("Out of milk")); } else { resolve(drink); } }, 1000); });}async function serve(drink: string): Promise<void> { try { const ready = await brew(drink); console.log("Ready:", ready); } catch (error) { console.log("Sorry, no latte"); }}serve("Latte");console.log("Order taken");
It prints Order taken, and a second later Sorry, no latte. When
Node stops on an error that a try should have caught, look at the
line inside the try: if it calls a function that gives back a
promise, and there is no await in front of it, the try was over
before the error came.
brewTea gives back a promise that is rejected at once. Wrap the
await in serveTea in a try / catch, so that the program prints
Sorry: Out of tea instead of stopping.
Loading the editor…
Exercise · Fix the error
Let the try wait
main has a try, yet the catch never runs: the program stops on
Error: Out of milk. Add one word so that it prints Sorry: Out of milk.
Loading the editor…
Recap
Recap · 3 questions
Check yourself
What does await do when its promise is rejected?
Check yourself
What does throw do inside an async function?
Check yourself
Why does try { serve("Latte"); } not catch its error?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
Errors in async code: try around await
What things are
Word
What it means
Rejected
The wait went wrong; the promise holds a reason
Reason
What a promise was rejected with, usually an Error
reject
Ends the wait as failed, with the reason you pass
Code
Write
To
(resolve, reject) => …
Give new Promise both ways to end the wait
reject(new Error("…"))
Reject the promise, and say why
await brew(drink)
Inside a try: a failed wait goes to its catch
throw in an async function
Reject the function's promise
Rules
Rule
What it means
await throws the reason
On its own line; the next lines are skipped
A rejection nobody catches
Node prints its reason and stops
The try holds the await
A try without await is over too soon
Anything can be rejected
So a try's catch gets it as unknown
Where to go next
You can now make a promise that is rejected, catch its error with a
try around await, catch what an async function throws the same
way, and tell why a try without await catches nothing.
Next is Catching what you do not await: .catch and unknown.
TaskKit's reminders are calls it does not await, on purpose, so no
try can hold them. That lesson catches their errors on the promise
itself, and closes a hole in the type TypeScript gives that error.
Before you move on, open serve.ts and put back the serve of the
second section, whose catch checks instanceof Error. Under
serve("Latte"); add serve("Flat white");. Predict what the program
prints and when, then run it. Then delete serve.ts from the
taskkit folder: it is not part of TaskKit.