typestar

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

  1. Returning a value passes it on; returning a promise waits for it.
  2. One catch at the end covers every step above it.
  3. finally runs either way and passes the result through.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 5 in Promises, step 3 of 19 in Promises & async.

← Previous Next →