我已将代码重组为 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,然后使用库提供的 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
});
}
与仅在 ES6 中可用的 Promise.all
之后的回调中的参数解构不同,在 ES5 中,then
调用将被许多 Promise 库提供的漂亮的辅助方法所取代( Q 、 Bluebird 、 when 、...): .spread(function(resultA, result) B) { ...
.
Bluebird 还具有专用的 join
function用更简单(更高效)的构造替换 Promise.all
+spread
组合:
…
return Promise.join(a, b, function(resultA, resultB) { … });
关于javascript - 如何访问 .then() 链中先前的 Promise 结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36384258/