liveBook · Manning

Nested promise

As explained in The Joy of JavaScript

A promise arrangement in which one Promise is returned from another Promise reaction so the inner asynchronous work rejoins the outer chain.

A nested promise returns asynchronous work from a promise reaction, allowing the inner operation to rejoin the outer chain instead of becoming an independent branch. This supports linear flows while combining data from multiple asynchronous actions. section 8.2.3

Use nesting carefully:

  • Return the inner Promise. Omitting return lets its result or error escape the main chain, bypassing later handlers. section 8.2.3 section 8.2.3
  • Plan error propagation explicitly: then(onRejected) and catch handle failures at different points in the chain. section 8.2.3
  • Prefer a promise combinator when independent endpoint responses must be merged; nesting is an alternative for expressing the flow. section 8.2.3

Joining an inner chain

Promise.resolve('aabbcc') .then(unique) .then(data => Promise.resolve(data) .then(join) .then(() => { throw new Error('Nested Ooops!') }) ) .then(toUpper) .catch(({message}) => console.error(message)); Returning the inner Promise keeps its result and error connected to the outer chain. section 8.2.3

Listing 8.6 Nested promise
const concat = arr1 => arr2 => arr1.concat(arr2);
 
Promise.resolve('aabbcc')
  .then(unique)
  .then(abc => 
    Promise.resolve('ddeeff')       #1
       .then(unique)
       .then(def => abc.concat(def))       
  )
  .then(join)
  .then(toUpper); // 'ABCDEF' 

Inspect a concrete nested chain that combines transformed values before continuing with later reactions. section 8.2.3

How The Joy of JavaScript covers it

How deep it goes
Explains chaining, data and error propagation, missing returns, recovery, and combinator tradeoffs through JavaScript examples.
Examples
Uses value transformations, combined endpoint-style data, detached inner promises, rejoined errors, and default-value recovery.
What it assumes
Assumes familiarity with Promise, then, catch, asynchronous actions, and promise chains.
What you can do after
Apply it to compose asynchronous operations and diagnose detached results or unhandled errors caused by omitted returns.
How it connects
Connects promise chaining with error handling, promise combinators, and asynchronous data composition.

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.