0

I have a promise chain like so

functionOne()
.catch(errorHandlerOne)
.then(functionTwo)        // calls functionTwo(responseOne)
.catch(errorHandlerTwo)
.then(functionThree)      // calls functionThree(responseTwo)
.catch(errorHandlerThree)
.finally(finalHandler)

This might seem to be an obvious answer, but my question is this:

I can access the responseOne in functionTwo() fine, but how can I access the responseOne in functionThree() or finalHandler()?

Edit: I thought about assigning it to a variable and accessing it later, but it seems to be quite hacky and against the flow of the promise chain. I'm looking for a better way

nikjohn
  • 20,026
  • 14
  • 50
  • 86

1 Answers1

1

how can I access the responseOne in functionThree() or finalHandler()?

By passing them forward in some way, as the return value of the then callback (or the resolution value of a promise it returns, which is effectively the same thing).

Example:

function asyncOp(name) {
  return new Promise(resolve => {
    resolve(name);
  });
}
asyncOp("one")
  .then(result1 => {
    return asyncOp("two")
      .then(result2 => [result1, result2]);
  })
  .then(results => {
    console.log("results", results);
  });

An array like that is just one option; you could use an object, you could store the interim results in variables the handler close over, ...

Same example in ES5 (just in case someone needs it):

function asyncOp(name) {
  return new Promise(function(resolve) {
    resolve(name);
  });
}
asyncOp("one")
  .then(function(result1) {
    return asyncOp("two")
      .then(function(result2) {
        return [result1, result2];
      });
  })
  .then(function(results) {
    console.log("results", results);
  });
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • My understanding is that the return value needs to be a promise in order for the chain to work properly. How can I make this work? – nikjohn Oct 21 '16 at 10:43
  • @nikjohn: No, it doesn't. If you return a non-"thenable" value from a `then` or `catch` callback, it's the same as returning a promise that's already resolved with that value. E.g., `return 42;` and `return Promise.resolve(42);` effectively do the same thing. – T.J. Crowder Oct 21 '16 at 10:44
  • 1
    Ah brilliant. This solves it! – nikjohn Oct 21 '16 at 10:58