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
