liveBook · Manning

Then method

As explained in Secrets of the JavaScript Ninja, Third Edition

A then method accepts fulfillment and rejection callbacks, allowing an object to participate in promise-like resolution.

A promise’s then method registers fulfillment and rejection callbacks and returns a new promise. The returned promise starts pending and settles according to the callback that runs. section 8.1.2

Callback results determine how the next promise settles:

  • Returning a value fulfills the new promise with that value, following promise resolution rules. section 8.1.2
  • Throwing an error rejects it; returning a promise makes it follow that promise’s outcome. section 8.1.2
  • Callbacks never run synchronously. Calling then on an already-settled promise queues its callback as a microtask, before pending timeouts. section 8.1.4
Listing 8.3 Using promise chaining to handle a fetch result
fetch("https://jsonplaceholder.typicode.com/posts/1") #A
  .then((response) => { #B
    if (!response.ok) { #C
      throw new Error(`Status code ${response.status}`); #D
    }
    return response.json(); #E
  })
  .then((json) => { #F
    console.log(json); #F
  }) #F
  .catch((reason) => { #G
    console.error(`Request failed: ${reason}`); #G
  }) #G
  .finally(() => { #H
    console.log("Request finished"); #H
  }); #H

A fetch chain checks the response, returns parsed JSON, handles failures in one catch, and runs finally whether the chain fulfills or rejects. section 8.1.2

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Explains callback outcomes, returned-promise resolution, and microtask timing through worked examples.
Examples
Uses a fetch request with response validation, JSON parsing, catch, and finally, plus a timeout ordering demonstration.
What it assumes
Assumes familiarity with promises and fulfillment or rejection; defines settled promises as those that remain fulfilled or rejected.
What you can do after
Apply it to chain asynchronous operations and route failures to a shared catch handler.
How it connects
Connects promises with fetch, catch, finally, and the microtask queue.

Also explained in

Compare how 6 books explain then method →

Related concepts

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