【发布时间】:2020-01-15 06:04:14
【问题描述】:
我的代码中有下一个函数可能会因以下几个原因而中断执行:
const getAndCheckItem = async (itemId) => {
try {
const item = await getItem(itemId);
if(item.firstFail) {
throw "First fail";
}
if(item.secondFail) {
throw "Second fail";
}
if(notGood(item)) {
throw "Third fail";
}
return item;
}
catch(err) {
return Promise.reject(err);
}
};
如果我按以下方式在其他异步函数中调用它,一切都很好,并且任何内部抛出都会被处理:
try {
item = await getAndCheckItem(ids[0]);
}
catch(err) {
// handle error
}
但是,当我为多个 id 调用函数时:
try {
items = await Promise.all([ids.map(value => getAndCheckItem(value))]);
}
catch(err) {
// handle error
}
如果发生任何内部抛出,我会收到未处理的承诺拒绝。我了解 Promise.all() 将任何返回的非承诺值视为已解决的承诺。但是,Promise.reject(err) 应该返回一个 Promise 并因此得到处理。有什么问题?
【问题讨论】:
-
尝试删除
ids.map上的方括号。map()已经返回一个数组 -
@CristopherNamchee 谢谢您,先生!我花了几个小时来定位错误,阅读文章并改变我对宇宙的理解,但像往常一样,看错了地方。 :)
标签: javascript node.js asynchronous promise async-await