liveBook · Manning

Then method

As explained in Functional Programming in JavaScript

A Promise method that registers callbacks to run when the promise settles and returns a new promise for chaining.

The then method registers success and error callbacks for a Promise and returns another Promise. It applies transformations to a value that will exist later, allowing dependent asynchronous work to read like a sequence instead of nested callbacks. section 8.2

Waiting for an asynchronous result

var promiseDemo = new Promise(function(resolve, reject) { Scheduler.delay5(function () { resolve('Done!'); }); }); promiseDemo.then(function(status) { console.log('After 5 seconds, the status is: ' + status); }); Each then callback receives the fulfilled value. A second optional callback can handle rejection, or error handling can be deferred to one catch at the end. section 8.2

Chaining with then supports several useful patterns:

  • Transform data through successive asynchronous steps without creating nested callback levels. section 8.2
  • Promisify callback-based APIs such as getJSON, then handle failures locally or with a final catch. section 8.2
  • Combine sequential then stages with Promise.all when several requests can run concurrently. section 8.2
Figure 8.6. A sequence of chained promises joined via the then method. Each then clause is executed serially with one promise value after the next as soon as each is fulfilled.

A sequence diagram makes the value flow through serial then clauses easy to follow. section 8.2

How Functional Programming in JavaScript covers it

How deep it goes
Explains callback arguments, serial chaining, and error placement, then extends the pattern to Promise.all.
Examples
Uses delayed resolution, promisified getJSON requests, chained student data processing, and concurrent grade retrieval.
What it assumes
Assumes basic callback-based asynchronous behavior, then builds Promise usage from construction through chaining.
What you can do after
Apply it via JavaScript Promise APIs to chain transformations, sequence requests, and handle failures.
How it connects
Connects promises with callbacks, functors, monads, catch, and Promise.all.

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 Functional Programming in JavaScript. The section links point to the parts of the book it draws on.