liveBook · Manning

Rejected state

As explained in Secrets of the JavaScript Ninja, Third Edition

The rejected state is a promise state indicating that the asynchronous operation failed with a rejection reason.

A promise is rejected when its asynchronous operation fails. Its associated value is the rejection reason, and once rejected, the promise is settled: its state and value cannot change. section 8.1.1

A promise can become rejected in these ways:

  • Calling reject(reason) in the executor rejects it with that reason. section 8.1.1
  • Throwing from the executor also rejects it; throwing in a then callback rejects the promise returned by then. section 8.1.1 section 8.1.2
Figure 8.1 The possible states of a promise: pending, fulfilled, rejected. The value associated with the rejected state is often called a reason.

The diagram shows rejection as one of the three promise states and labels its associated value as a reason. section 8.1.1

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

The fetch chain throws when the response is unsuccessful and sends request, status, or JSON errors to catch. section 8.1.2

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Defines rejection, settlement, and executor transitions, then traces thrown errors through promise chaining and catch handlers.
Examples
Uses reject(reason), executor throws, and a fetch chain that throws on a bad response and handles failure with catch.
What you can do after
Diagnose failures across a fetch chain by routing request, status, and JSON errors to one catch handler.
How it connects
Connects promise rejection to fulfillment, settlement, then callbacks, catch, and try/catch error handling.

Also explained in

Compare how 2 books explain rejected state →

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.