javascript · level 3 · unit 5 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
links steps together; handles a failure above it.
Before await existed, code used .then: promise.then((value) => ...) runs a function once the promise resolves. It returns a new promise, so you can add another .then, building a chain. Each step receives whatever the step before it returned.
If any step throws or rejects, the steps after it are skipped and the nearest .catch runs, like catch after try. .finally runs at the end either way. You will meet chains in older code, so learn to read both styles.
const url = "https://api.example.com/menu";
await fetch(url)
.then((reply) => reply.json())
.then((menu) => menu.filter((dish) => dish.vegan))
.then((vegan) => console.log(vegan.map((dish) => dish.name)))
.catch((error) => console.log("Menu failed:", error.name))
.finally(() => console.log("Done")); Gwecode answers requests to https://api.example.com with a practice server, so these lessons never need the real internet.
guess first
A step throws halfway down. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
new Promise((resolve) => resolve(2))
.then((n) => n * 10)
.then((n) => { throw new Error(`bad ${n}`); })
.then((n) => console.log("never", n))
.catch((error) => { console.log(error.message); return 5; })
.then((n) => console.log("after", n));
your turn
Your turn. Add a step to the chain.
The practice server sends a basket of prices in pence. Fill in the step that turns the pence total into pounds.
fix it
The weather never arrives. Can you fix it?
- The second step receives
undefined. What does the first step hand on? - Curly brackets after
=>make a block, and a block only hands something on withreturn. - Change line 3 to
.then((reply) => reply.json()), then press run.
nailed it
you can read and write promise chains. :D
.thenpasses each step's return value to the next.- One
.catchhandles a failure anywhere above it. - Forget to return in a step and the next gets
undefined.
new words in your collection
- .then
- .catch
This lesson isn’t saved. A free account remembers every lesson you finish.