我已将代码重组为 promises ,并构建了一个美妙的长扁平 promise 链 , 由多个 .then()
组成回调。最后我想返回一些复合值,并且需要访问多个中间 promise 结果 .但是,序列中间的分辨率值不在最后一个回调的范围内,我该如何访问它们?
function getExample() {
return promiseA(…).then(function(resultA) {
// Some processing
return promiseB(…);
}).then(function(resultB) {
// More processing
return // How do I gain access to resultA here?
});
}
最佳答案
断链
当您需要访问链中的中间值时,您应该将链拆分为您需要的单个部分。与其附加一个回调并以某种方式尝试多次使用其参数,不如将多个回调附加到同一个 Promise - 无论您需要结果值的任何地方。别忘了,promise just represents (proxies) a future value !除了从线性链中的另一个导出一个 promise 之外,使用库提供给您的 promise 组合器来构建结果值。
这将导致非常简单的控制流程、清晰的功能组合,因此易于模块化。
function getExample() {
var a = promiseA(…);
var b = a.then(function(resultA) {
// some processing
return promiseB(…);
});
return Promise.all([a, b]).then(function([resultA, resultB]) {
// more processing
return // something using both resultA and resultB
});
}
而不是在
Promise.all
之后的回调中解构参数仅在 ES6 中可用,在 ES5 中 then
call 将被许多 Promise 库(Q,Bluebird,when,...)提供的漂亮的辅助方法所取代:.spread(function(resultA, resultB) { …
.Bluebird 还具有专用的
join
function替换 Promise.all
+ spread
结合更简单(更有效)的构造:…
return Promise.join(a, b, function(resultA, resultB) { … });
关于javascript - 如何在 .then() 链中访问先前的 promise 结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35457244/