Home >Web Front-end >JS Tutorial >How to Manage Dependent Results in JavaScript Promise Chains?
How to Handle Dependent Results in Promise Chains
Your question asks how to utilize previous results within a sequence of Promise-based HTTP requests. To address this, let's first consider various strategies for sharing data across dependent promises. The choice of strategy depends on your need for access to all prior results or only the most recent one.
Feeding Results Sequentially
In this model, the result of each request is passed as an argument to the next. However, accessing previous results becomes challenging.
Assigning Results to Higher Scope
Alternatively, you can store the results in variables in a higher scope. This allows for accessing all previous results.
Accumulating Results in an Object
This approach involves creating an object to accumulate results. Each request adds its result to the object, making all previous data available.
Nested Promise Chains
Nested promises preserve access to previous results. Each successive layer provides a scope where all earlier results are accessible.
Breaking the Chain with Promise.all()
If some requests can operate independently, you can use Promise.all() to wait for their completion. This allows you to obtain their results asynchronously.
Using Async/Await in ES7
In ES7, async/await can simplify the sequencing of asynchronous operations. Results are available within the same scope, eliminating the need for multiple .then() handlers.
Applying to Your Example
In your specific case, where an API key is passed between multiple HTTP requests, you could:
var r1, r2, r3; callhttp("172.16.28.200", payload).then(function(result1) { r1 = result1.data; // Extract the API key return callhttp("172.16.28.200", payload); }).then(function(result2) { r2 = result2.data; // r1 contains the API key from the previous request return callhttp("172.16.28.200", payload); }).then(function(result3) { r3 = result3.data; // r1 and r2 contain the API keys from the previous requests });
The above is the detailed content of How to Manage Dependent Results in JavaScript Promise Chains?. For more information, please follow other related articles on the PHP Chinese website!