显式直通
类似于嵌套回调,此技术依赖于闭包。然而,链保持不变——不是只传递最新的结果,而是为每一步传递某个状态对象。这些状态对象累积先前操作的结果,传递稍后将再次需要的所有值加上当前任务的结果。
function getExample() {
return promiseA(…).then(function(resultA) {
// some processing
return promiseB(…).then(b => [resultA, b]); // function(b) { return [resultA, b] }
}).then(function([resultA, resultB]) {
// more processing
return // something using both resultA and resultB
});
}
这里,小箭头b => [resultA, b]是在resultA上关闭的函数,并将两个结果的数组传递给下一步。它使用参数解构语法将其再次分解为单个变量。
在ES6提供解构之前,许多承诺库(Q, Bluebird, when,…)提供了一个漂亮的助手方法,名为.spread()。它接受一个带有多个参数的函数——每个数组元素一个参数——作为.spread(function(resultA, resultB) {....
当然,这里需要的闭包可以通过一些辅助函数进一步简化,例如。
function addTo(x) {
// imagine complex `arguments` fiddling or anything that helps usability
// but you get the idea with this simple one:
return res => [x, res];
}
…
return promiseB(…).then(addTo(resultA));
或者,您可以使用Promise。所有这些都是为了产生数组的承诺:
function getExample() {
return promiseA(…).then(function(resultA) {
// some processing
return Promise.all([resultA, promiseB(…)]); // resultA will implicitly be wrapped
// as if passed to Promise.resolve()
}).then(function([resultA, resultB]) {
// more processing
return // something using both resultA and resultB
});
}
你不仅可以使用数组,还可以使用任意复杂的对象。例如,用_。扩展或对象。在不同的helper函数中赋值:
function augment(obj, name) {
return function (res) { var r = Object.assign({}, obj); r[name] = res; return r; };
}
function getExample() {
return promiseA(…).then(function(resultA) {
// some processing
return promiseB(…).then(augment({resultA}, "resultB"));
}).then(function(obj) {
// more processing
return // something using both obj.resultA and obj.resultB
});
}
While this pattern guarantees a flat chain and explicit state objects can improve clarity, it will become tedious for a long chain. Especially when you need the state only sporadically, you still have to pass it through every step. With this fixed interface, the single callbacks in the chain are rather tightly coupled and inflexible to change. It makes factoring out single steps harder, and callbacks cannot be supplied directly from other modules - they always need to be wrapped in boilerplate code that cares about the state. Abstract helper functions like the above can ease the pain a bit, but it will always be present.