Home >Web Front-end >JS Tutorial >How Can I Access Previous Promise Results in a JavaScript .then() Chain?
Accessing Previous Promise Results in a .then() Chain
In the pursuit of structuring code using promises, a "flat promise chain" comprising several .then() callbacks may be created. However, accessing intermediate promise results within this chain can be challenging since they are not typically in scope for subsequent callbacks.
Breaking the Chain
To access intermediate values, consider breaking the chain into smaller pieces. Instead of attaching a single callback and attempting to utilize its parameter repeatedly, attach multiple callbacks to the same promise where each result value is required. By incorporating promise combinators provided by the library, the result value can be constructed.
This approach simplifies control flow, enhances composition, and facilitates modularization.
Modified Code Example:
function getExample() { var a = promiseA(...); var b = a.then(function (resultA) { // some processing return promiseB(...); }); return Promise.all([a, b]).then(function ([resultA, resultB]) { // more processing return // something using both resultA and resultB }); }
ES5 alternative:
… return a.then(function(resultA) { return b.then(function(resultB) { // more processing return // something using both resultA and resultB }); });
Bluebird solution:
… return Promise.join(a, b, function(resultA, resultB) { … });
The above is the detailed content of How Can I Access Previous Promise Results in a JavaScript .then() Chain?. For more information, please follow other related articles on the PHP Chinese website!