Chaining and Sharing Prior Results with Promises
In your code, you're trying to make multiple HTTP requests using the Bluebird promise library and you need to pass the response data from one request to the next. To achieve this, you can utilize several strategies to chain and share prior results with promises.
1. Chaining Promises
You can chain promises by returning a promise from within .then() handlers. Each subsequent .then() will receive the result of the previous promise. In your case, you can chain the requests as follows:
callhttp("172.16.28.200", payload).then(function(first) { return callhttp("172.16.28.200", first); }).then(function(second) { return callhttp("172.16.28.200", second); });
2. Accumulating Results
Alternatively, you can accumulate all the results into a single object. Create an object to store the results and pass it as an argument to the subsequent requests:
var results = {}; callhttp("172.16.28.200", payload).then(function(first) { results.first = first; return callhttp("172.16.28.200", first); }).then(function(second) { results.second = second; return callhttp("172.16.28.200", second); }).then(function(third) { results.third = third; });
3. Nested Promises
If you need access to all the previous results, you can nest promises. Each nested promise will have access to the results of the outer promises:
callhttp("172.16.28.200", payload).then(function(first) { return callhttp("172.16.28.200", first).then(function(second) { return callhttp("172.16.28.200", second).then(function(third) { // Access all three results here }); }); });
4. Breaking the Chain
If some requests can proceed independently, you can break the chain and use Promise.all() to collect the results when they are all complete:
var p1 = callhttp("172.16.28.200", payload); var p2 = callhttp("172.16.28.200", payload); var p3 = callhttp("172.16.28.200", payload); Promise.all([p1, p2, p3]).then(function(results) { // All three results are available in the `results` array });
5. Using async/await (ES7 feature)
In ES7, you can simplify sequencing asynchronous operations using async/await. This allows you to use regular synchronous syntax, and the intermediate results are available in the same scope:
async function myFunction() { const first = await callhttp("172.16.28.200", payload); const second = await callhttp("172.16.28.200", first); const third = await callhttp("172.16.28.200", second); // Access all three results here } myFunction().then(result => {}).catch(error => {});
The above is the detailed content of How Can I Chain and Share Results from Multiple HTTP Requests Using Bluebird Promises?. For more information, please follow other related articles on the PHP Chinese website!