Home > Web Front-end > JS Tutorial > How Can I Access Previous Promise Results in a JavaScript .then() Chain?

How Can I Access Previous Promise Results in a JavaScript .then() Chain?

Mary-Kate Olsen
Release: 2024-12-27 14:59:10
Original
906 people have browsed it

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
  });
}
Copy after login

ES5 alternative:

…
return a.then(function(resultA) {
  return b.then(function(resultB) {
    // more processing
    return // something using both resultA and resultB
  });
});
Copy after login

Bluebird solution:

…
return Promise.join(a, b, function(resultA, resultB) { … });
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template