【发布时间】:2015-11-19 18:24:10
【问题描述】:
在使用多个 Promise 和 Promise.all 时如何避免 Promise 构造函数反模式?
假设我有以下代码:
getFoo = function() {
return new Promise(function(resolve, reject) {
var promises = [];
promises.push(new Promise(function(resolve, reject) => {
getBar1().then(function(bar1) {
processBar1(bar1);
resolve(bar1);
});
}));
promises.push(new Promise(function(resolve, reject) => {
getBar2().then(function(bar2) {
processBar2(bar2);
resolve(bar2);
});
}));
Promise.all(promises).spread(function(bar1, bar2) {
var result = processBothBars(bar1, bar2);
resolve(result);
});
});
}
它提出了反模式的一些基本问题,错误被吞噬,以及厄运金字塔。
顺便说一句,我正在使用蓝鸟。
【问题讨论】:
-
而不是顶部的
return new Promise(..,return Promise.all(...? -
@KevinB 但内部承诺仍会吞下错误
-
为什么需要内在的承诺?为什么不能将 getBar1() 的返回值推送到数组?我对 bluebird 不太熟悉,但是,如果它遵循原生 Promise 功能,那么上面的 sn-p 中根本不需要
new Promise。
标签: javascript node.js promise ecmascript-6 bluebird