Chaining in JavaScript
Each then returns a new promise, so the value flows down the chain.
function fetchSteps(lang) {
return Promise.resolve({ lang, steps: lang.length * 10 });
}
fetchSteps("javascript")
.then((tour) => ({ ...tour, label: tour.lang.toUpperCase() }))
.then((tour) => fetchSteps(tour.label.toLowerCase()))
.then((tour) => console.log("steps:", tour.steps))
.catch((error) => console.log("failed:", error.message))
.finally(() => console.log("done"));
How it works
- Returning a value passes it on; returning a promise waits for it.
- One
catchat the end covers every step above it. finallyruns either way and passes the result through.
Keywords and builtins used here
Promisecatchfinallyfunctionreturn
The run, in numbers
- Lines
- 10
- Characters to type
- 376
- Tokens
- 121
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 76 seconds.
Step 3 of 5 in Promises, step 3 of 19 in Promises & async.