liveBook · Manning

Then method

As explained in The Joy of JavaScript

A Promise method used to register fulfillment and rejection handlers and compose promise-based workflows.

The then method registers reactions on a Promise and returns another Promise, allowing fulfillment values and errors to move through a composed asynchronous workflow. section 8.2.2 section 8.2.3

Use then to structure transformations and preserve the intended flow:

  • Chain calls when each transformation should receive the preceding result: Promise.resolve('aabbcc').then(unique).then(join).then(toUpper). section 8.2.3
  • Return nested promises from handlers so their results and failures rejoin the main chain; returned promises are flattened automatically. section 8.2.2 section 8.2.3
  • Attach catch for errors that travel through the linked chain, or recover with a default value when appropriate. section 8.2.3

A chain is not multiple handlers on one promise

const p = Promise.resolve('aabbcc'); p.then(unique); p.then(join); p.then(toUpper); These calls all receive the original value and create separate promises. Chaining the returned promise instead—p.then(unique).then(join).then(toUpper)—passes each transformed result to the next step. section 8.2.3

Listing 8.4 Fully linked chain of promises
Promise.resolve('aabbcc')
    .then(unique)            #1
    .then(join)              #1
    .then(toUpper);          #1

A compact listing shows the intended unidirectional transformation pipeline. section 8.2.3

How The Joy of JavaScript covers it

How deep it goes
Explains returned promises, value propagation, automatic flattening, broken chains, nested chains, and error recovery.
Examples
Demonstrates string transformations, fully linked and broken chains, nested promises, error propagation, and default-value recovery.
What it assumes
Assumes familiarity with JavaScript functions and Promise states while relating Promise behavior to Validation and composition.
What you can do after
Apply it to build composable Promise pipelines, join nested asynchronous work, and diagnose detached handlers or unhandled rejections.
How it connects
Connects Promise#then with Promise, Promise#catch, composition, Validation, and algebraic data types.

Also explained in

Compare how 5 books explain then method →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Joy of JavaScript. The section links point to the parts of the book it draws on.