Home > Web Front-end > JS Tutorial > How to Access Previous Results When Chaining Promises in JavaScript?

How to Access Previous Results When Chaining Promises in JavaScript?

Susan Sarandon
Release: 2024-11-28 10:04:12
Original
527 people have browsed it

How to Access Previous Results When Chaining Promises in JavaScript?

Chaining Promises and Sharing Previous Results

In this scenario, you need to make a series of HTTP requests, passing response data from one request to the next using Bluebird's Promise.join. The challenge lies in accessing the response data from the first request.

To achieve this, you can employ one of several approaches:

Option 1: Feed Result of One to the Next

This approach involves chaining promises directly, passing the result of one request as input to the next. Each subsequent .then() handler has access only to the most recent result:

Promise.join(
    callhttp("172.16.28.200", payload),
    callhttp("172.16.28.200", payload),
    callhttp("172.16.28.200", payload)
).then(function(first, second, third) {
    console.log([first, second, third]);
});
Copy after login

However, this approach does not allow access to previous results.

Option 2: Assign Intermediate Results to Higher Scope

Here, you assign intermediate results to variables declared in a higher scope. This provides access to all previous results in subsequent .then() handlers:

var r1, r2, r3;
Promise.join(
    callhttp("172.16.28.200", payload),
    callhttp("172.16.28.200", payload),
    callhttp("172.16.28.200", payload)
).then(function(result1, result2, result3) {
    r1 = result1;
    r2 = result2;
    r3 = result3;
});
Copy after login

Option 3: Accumulate Results in One Object

This approach involves creating an object to accumulate results as they become available. Each .then() handler adds its result to the object, allowing access to all previous results:

var results = {};
Promise.join(
    callhttp("172.16.28.200", payload),
    callhttp("172.16.28.200", payload),
    callhttp("172.16.28.200", payload)
).then(function(result1, result2, result3) {
    results.result1 = result1;
    results.result2 = result2;
    results.result3 = result3;
});
Copy after login

Option 4: Nest Promises

Nesting promises allows you to access all previous results within the nested scopes:

Promise.join(
    callhttp("172.16.28.200", payload),
    callhttp("172.16.28.200", payload),
    callhttp("172.16.28.200", payload)
).then(function(result1) {
    // result1 is available here
    return Promise.join(
        callhttp("172.16.28.200", payload),
        callhttp("172.16.28.200", payload)
    ).then(function(result2) {
        // result1 and result2 are available here
        return Promise.join(
            callhttp("172.16.28.200", payload)
        ).then(function(result3) {
            // result1, result2 and result3 are available here
        });
    });
})
Copy after login

Option 5: Break the Chain into Independent Pieces

If some parts of the chain can execute independently, you can break the chain, launch them separately, and use Promise.all() to collect the results:

var p1 = callhttp("172.16.28.200", payload);
var p2 = callhttp("172.16.28.200", payload).then(function(result2) {
    return someAsync(result2);
}).then(function(result2a) {
    return someOtherAsync(result2a);
});
var p3 = callhttp("172.16.28.200", payload).then(function(result3) {
    return someAsync(result3);
});
Promise.all([p1, p2, p3]).then(function(results) {
    // multiple results available in results array
    // that can be processed further here with
    // other promises
});
Copy after login

Option 6: Sequence with await in ES7

Promises provide a way to sequence asynchronous operations. In ES7, you can use await to sequence these operations, simplifying the process:

async function someFunction() {
    const r1 = await callhttp("172.16.28.200", payload);

    // can use r1 here to formulate second http call
    const r2 = await callhttp("172.16.28.200", payload);

    // can use r1 and r2 here to formulate third http call
    const r3 = await callhttp("172.16.28.200", payload);

    // do some computation that has access to r1, r2 and r3
    return someResult;
}

someFunction().then(result => {
    // process final result here
}).catch(err => {
    // handle error here
});
Copy after login

Note that each option has its own advantages and disadvantages. Choose the one that best fits the specific requirements of your application.

The above is the detailed content of How to Access Previous Results When Chaining Promises in JavaScript?. 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