Break the chain(断链)
When you need to access the intermediate values in your chain, you should split your chain apart in those single pieces that you need.
(当需要访问链中的中间值时,应将链分成所需的单个部分。)
Instead of attaching one callback and somehow trying to use its parameter multiple times, attach multiple callbacks to the same promise - wherever you need the result value.(不必附加一个回调并以某种方式尝试多次使用其参数,而是将多个回调附加到同一promise-无论何时需要结果值。)
Don't forget, a promise just represents (proxies) a future value !(不要忘记, 承诺只是代表(代理)未来的价值 !)
Next to deriving one promise from the other in a linear chain, use the promise combinators that are given to you by your library to build the result value.(除了从线性链中的另一个承诺中推导一个承诺之外,还使用库提供给您的承诺组合器来构建结果值。)
This will result in a very straightforward control flow, clear composition of functionalities and therefore easy modularisation.
(这将导致非常简单的控制流程,清晰的功能组成,因此易于模块化。)
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
});
}
Instead of the parameter destructuring in the callback after Promise.all
that only became available with ES6, in ES5 the then
call would be replaced by a nifty helper method that was provided by many promise libraries ( Q , Bluebird , when , …): .spread(function(resultA, resultB) { …
.
(与其在Promise.all
之后的回调中进行参数解构(仅在ES6中可用),在ES5中, then
调用将由许多promise库( Q , Bluebird , when ,…)提供的漂亮的助手方法代替: .spread(function(resultA, resultB) { …
。)
Bluebird also features a dedicated join
function to replace that Promise.all
+ spread
combination with a simpler (and more efficient) construct:
(蓝鸟还具有专用的join
功能,可以用更简单(更高效)的结构替换Promise.all
+ spread
组合:)
…
return Promise.join(a, b, function(resultA, resultB) { … });
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…