Chain Steps With .then()

In Exercise: Read the Family’s Picks, your code reported everyone’s picks. An ID doesn’t get Tolu to the painting, though. The planning script has to ask the museum’s kiosk about Tolu’s first pick, then find out which gallery it hangs in. Each step needs the result of the one before, and with callbacks, that’s where the nesting started.

In this lesson, you’ll link those steps into one chain with .then() that reads from top to bottom, and you’ll see what each handler hands to the next. Start by getting the first ID out of the picks, a step that doesn’t need the kiosk.

Pass a Value Down the Chain

A chain is only useful if each step can hand its result to the next. In Handle Results With .then() and .catch(), you learned that .catch() is attached to a new promise that .then() hands back. That new promise is what makes chains work.

Every call to .then() returns a new promise, and when your handler returns a plain value, that promise is fulfilled with it. When your handler returns a promise, the new promise follows that promise’s outcome instead.

Keep working in your museum folder, where picks.txt still holds the family’s picks:

Language: Text Filename: picks.txt
Tolu: 28560, 111628
Grandma Bisi: 27992
Folake: 6565, 20684
Tunde: 16568

Next to it, save this script as chain_pick.mjs. Each handler does one small job on the text of picks.txt:

Language: JavaScript Filename: chain_pick.mjs
import { readFile } from "node:fs/promises";

readFile("picks.txt", "utf8")
  .then((picks) => picks.split("\n")[0])
  .then((line) => line.split(": ")[1].split(", ")[0])
  .then((id) => console.log(`Tolu's first pick: ${id}`));

Run it, and the ID comes out of the last handler:

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.