New to promises; consider the case where there is promiseA() and promiseB(a) which depends on the first result, and I want to collect results from both and perform a third action doSomething(a, b):
Style A (closure/nesting)
promiseA().then(function (resultA) {
return (promiseB(resultA).then(function (resultB) {
doSomething(resultA, resultB);
}));
});
Style B (return value/chaining)
promiseA().then(function (resultA) {
return Promise.all([resultA, promiseB(resultA)]);
}).spread(function (resultA, resultB) {
doSomething(resultA, resultB);
});
As far as I can tell, these are equivalent:
- Same sequencing constraint between
promiseAandpromiseB - Final promise returns
undefined - Final promise is rejected if
promiseAorpromiseBare rejected, ordoSomethingthrows.
As a matter of style, Style B reduces indentation (pyramid of doom).
However, Style B is more difficult to refactor. If I need to introduce an intermediate promiseA2(a) and doSomething(a, a2, b), I need to modify 3 lines (Promise.all, spread, doSomething), which can lead to mistakes (accidental swapping etc), while with Style A I only to modify 1 line (doSomething) and the variable name makes it clear which result it is. In large projects, this may be significant.
Are there other non-functional trade-offs between the two styles? More/less memory allocation in one vs the other? More/fewer turns around the event loop? Better/worse stack traces on exceptions?