在使用多个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);
});
});
}
它提出了反模式的一些基本问题,错误被吞噬,以及厄运的金字塔.
我正在使用蓝鸟BTW.
解决方法:
你可以一起摆脱新的Promise.
getFoo = function() {
var promises = [];
promises.push(getBar1().then(function(bar1) {
processBar1(bar1);
return bar1;
}));
promises.push(getBar2().then(function(bar2) {
processBar2(bar2);
return bar2;
}));
return Promise.all(promises).spread(function(bar1, bar2) {
var result = processBothBars(bar1, bar2);
return result;
});
}
// start mock
function getBar1() {
return Promise.resolve({name:'bar1',processed: false});
}
function getBar2() {
return Promise.resolve({name:'bar2',processed: false});
}
function processBar1(bar1) {
bar1.processed = true;
}
function processBar2(bar2) {
bar2.processed = true;
}
function processBothBars (bar1, bar2) {
return [bar1, bar2].filter(function (bar) {
return bar.processed;
}).map(function (bar) {
return bar.name;
});
}
Promise.prototype.spread = function (fn) {
return this.then(function (arr) {
return fn.apply(this, arr);
});
};
// end mock
var getFoo = function (fail) {
var promises = [];
promises.push(getBar1().then(function (bar1) {
processBar1(bar1);
if (fail) {
throw 'getBar1 Failed!';
}
return bar1;
}));
promises.push(getBar2().then(function (bar2) {
processBar2(bar2);
return bar2;
}));
return Promise.all(promises).spread(function (bar1, bar2) {
var result = processBothBars(bar1, bar2);
return result;
});
}
getFoo().then(function (result) {
console.log(result); // ['bar1', 'bar2']
});
getFoo(true).then(function (result) {
console.log(result); // doesn't happen
}).catch(function (e) {
console.error(e); // Error: getBar1 Failed!
});
.then返回一个promise,因此除非你想防止错误到达外部promise,否则不需要创建一个包装它的新的promise.