How to access results of a promise at a later part of a chain [duplicate]

岁酱吖の 提交于 2019-12-25 08:56:31

问题


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


回答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);
  });


来源:https://stackoverflow.com/questions/40174411/how-to-access-results-of-a-promise-at-a-later-part-of-a-chain

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!