2
return makeFirstPromise()
    .then(function(res1) {
       (...)
    })
    .then(function(res2) {
       (...)
    })
    .then(function(res3) {
        // **here I need to access res1**
    });

I would like to know if there is a best practice when I need to access to a previous promise result in a subsequent function of my promise chain.

I see two possible solutions:

var r1;
return makeFirstPromise()
    .then(function(res1) {
       r1 = res1;
       (...)
    })
    .then(function(res2) {
       (...)
    })
    .then(function(res3) {
        console.log(r1);
    });

or to nest the promises following the first but it visually breaks the chain sequence:

return makeFirstPromise()
    .then(function(res1) {
       (...)
       return secondPromise(res2)
           .then(function(res3) {
               console.log(res1);
           });
    });

Any idea?

1

2 Answers 2

3

Promise syntax is conceived to be used in the first way. The second syntax gets confusing very fast.
But don't forget to pass the result into the next promise.

var r1;
return makeFirstPromise()
    .then(function(res1) {
       r1 = res1;
       (...)
       return r1;
    })
    .then(function(r1) {
       (...)
    });
Sign up to request clarification or add additional context in comments.

3 Comments

The problem is my second promise already returns a value (res2).
Make an array [] or object {} out of the results.
Could leads to a complicated code if I don't control the second promise (like a nodejs function) but I prefer this solution over the variable declaration solution. Thanks.
2

Conceptually promises proxy values, the easiest way to use them with values is to use them as proxies. This is what they abstract:

var res1 = makeFirstPromise();
var res2 = res1.then(makeSecondPromise);
Promise.all([res1, res2]).spread(function(firstResult, secondResult){
    // access both here, no nesting or closure hacks required.
});

2 Comments

nice idea but I have a chain of promises and it could be the 7th that needs a result from the 3th promise, for instance.
Why would it matter? Also note that some promise implementations like Bluebird have a context you can pass around - look at Promise#bind at bluebird's API - that can also solve your problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.