我有一个像这样的 promise 链
functionOne()
.catch(errorHandlerOne)
.then(functionTwo) // calls functionTwo(responseOne)
.catch(errorHandlerTwo)
.then(functionThree) // calls functionThree(responseTwo)
.catch(errorHandlerThree)
.finally(finalHandler)
这似乎是一个显而易见的答案,但我的问题是:
我可以访问 responseOne
在functionTwo()
很好,但是我怎样才能访问 responseOne
在functionThree()
或finalHandler()
?
编辑:我考虑过将其分配给一个变量并稍后访问它,但它似乎非常hacky并且违背了 promise 链的流程。我正在寻找更好的方法
最佳答案
how can I access the responseOne in functionThree() or finalHandler()?
通过以某种方式将它们向前传递,作为 then
回调的返回值(或者它返回的 Promise 的解析值,这实际上是同一件事)。
示例:
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);
});
像这样的数组只是一种选择;您可以使用一个对象,您可以将临时结果存储在处理程序关闭的变量中,...
ES5 中的相同示例(以防万一有人需要):
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);
});
关于javascript - 如何访问链后面部分的 promise 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40174411/