Search code examples
javascriptasynchronouspromisechaining

How to access results of a promise at a later part of a chain


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


Solution

  • 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);
      });