打破枷锁
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. 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.
这将导致一个非常直接的控制流程,清晰的功能组合,因此易于模块化。
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之后的回调中进行参数解构。在ES5中,then调用将被许多承诺库(Q, Bluebird, when,…)提供的一个漂亮的助手方法所取代:.spread(function(resultA, resultB) {....
Bluebird还提供了一个专用的连接功能来取代承诺。All +扩展组合,更简单(更有效)的结构:
…
return Promise.join(a, b, function(resultA, resultB) { … });