In order to retrieve intermediate promise results within a flat promise chain, it is necessary to break the chain apart into separate segments.
Instead of relying on the parameter of a single callback to obtain intermediate values, it is recommended to utilize promise combinators to create the desired composite value. This approach ensures a clear and structured control flow, making modularization straightforward.
Consider the following 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 }); }
In this example, the promise combinator Promise.all is used to aggregate the results of a and b. The callback that follows Promise.all can then access and utilize both resultA and resultB to construct the composite value.
Libraries like Q, Bluebird, and when provide helper methods such as .spread to simplify the processing of multiple promise results in ES5.
… return Promise.all([a, b]).then(function(results) { results.spread(function(resultA, resultB) { … }); });
Bluebird offers a dedicated Promise.join function as a more efficient alternative to the Promise.all and .spread combination.
… return Promise.join(a, b, function(resultA, resultB) { … });
The above is the detailed content of How Can I Access Intermediate Promise Results in a Flat Promise Chain?. For more information, please follow other related articles on the PHP Chinese website!