【发布时间】:2018-08-05 20:16:24
【问题描述】:
我构建了这个我不理解的用例。
我想创建一个 Promise 数组(例如 var array)并添加解析数组中每个元素的所有 Promise。
可选地,对于数组的某些元素,我想进行额外的阐述,所以我链接另一个 Promise(在 if (e === 'b') 内)。
我希望Promise.all(array) 会捕获拒绝条件,但它会打印:
> node .\test.js
b is ok
all clear
(node:1304) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: 'b is ok' is NOT ok
为什么会这样? Promise.all 不管理链接?
thePromise 指向一个链接了另一个承诺的承诺。我认为所有thePromise 链都需要评估以考虑解决,而不仅仅是第一个。我错过了什么吗?
我注意到实际的解决方案是像这样重新分配承诺:
thePromise = thePromise.then((msg) => ....
示例代码:
const array = [];
const arrayData = ['a', 'b', 'c'];
arrayData.forEach((e) => {
let thePromise = newPromise(e);
if (e === 'b') {
thePromise.then((msg) => {
console.log(msg);
return newPromise(msg);
});
}
array.push(thePromise);
});
Promise.all(array)
.then(() => console.log('all clear'))
.catch(err => console.log('something goes wrong', err));
function newPromise(value) {
return new Promise((resolve, reject) => {
if (value === 'b is ok') {
reject(new Error(`'${value}' is NOT ok`));
} else {
resolve(`${value} is ok`);
}
});
}
谢谢你的解释
【问题讨论】:
标签: javascript promise es6-promise