莫回无
使用.catch()和Promise.all()确保正确处理拒绝,并且可以安全地使用Promises.all()而不面临未处理的拒绝。(编辑:每次讨论澄清:不是错误unhandled rejection但是简单地说,拒绝是不被代码处理的。Promise.all()会抛出第一个承诺,拒绝和意志视而不见其他的)。在下面的示例中,一个[错误,结果],.]数组返回以便于处理结果和/或错误。let myTimeout = (ms, is_ok) =>
new Promise((resolve, reject) =>
setTimeout(_=> is_ok ?
resolve(`ok in ${ms}`) :
reject(`error in ${ms}`),
ms));let handleRejection = promise => promise .then((...r) => [null, ...r])
.catch(e => [e]); (async _=> {
let res = await Promise.all([
myTimeout(100, true),
myTimeout(200, false),
myTimeout(300, true),
myTimeout(400, false)
].map(handleRejection));
console.log(res);})();但是,您可以从CATCH()中抛出,以停止等待所有的结果(并丢弃其余的结果)-您可以每次尝试/捕获块只执行一次,因此需要维护和检查旗标SADS_SOWN,以确保不会发生未处理的错误。let myTimeout = (ms, is_ok) =>
new Promise((resolve, reject) =>
setTimeout(_=> is_ok ?
resolve(`ok in ${ms}`) :
reject(`error in ${ms}`),
ms));let has_thrown = false;let handleRejection = promise => promise .then((...r) => [null, ...r])
.catch(e => {
if (has_thrown) {
console.log('not throwing', e);
} else {
has_thrown = 1;
throw e;
}
});(async _=> {
try {
let res = await Promise.all([
myTimeout(100, true),
myTimeout(200, false),
myTimeout(300, true),
myTimeout(400, false)
].map(handleRejection));
console.log(res);
} catch(e) {
console.log(e);
}
console.log('we are done');})();