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?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Guid
  • 2,137
  • 2
  • 20
  • 33
  • exact duplicate of [How do I access previous promise results in a .then() chain?](http://stackoverflow.com/questions/28250680/how-do-i-access-previous-promise-results-in-a-then-chain) – Bergi Jan 31 '15 at 10:58

2 Answers2

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) {
       (...)
    });
Clawish
  • 2,934
  • 3
  • 24
  • 28
  • The problem is my second promise already returns a value (res2). – Guid Dec 05 '14 at 16:08
  • Make an array `[]` or object `{}` out of the results. – Clawish Dec 05 '14 at 16:10
  • 1
    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. – Guid Dec 05 '14 at 16:14
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.
});
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • 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. – Guid Dec 06 '14 at 13:27
  • 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. – Benjamin Gruenbaum Dec 06 '14 at 13:33