我正在尝试使用 forEach
循环数组循环 async
JavaScript 中的回调。问题是,当我抛出异常时,它会给出
(node:2500) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 6)
虽然我在 forEach
之后有一个 catch block 。这是我的代码
async function func() {
try {
array.forEach(async (e) => {
try {
let bom = await BOMChild.findOne({
where: { id: e.id },
});
if (bom.BOMProductId || bom.BOMProductId === 0) {
throw {
name: " error",
description: `Description `,
};
}
} catch (e) {
throw e;
}
});
} catch (e) {
//exception caught
}
}
我做错了什么以及解决这个问题的可能方法是什么。 TIA
最佳答案
不幸的是,没有安全的方法可以将async
回调与forEach
结合使用。最简单的解决方案是以 async
方式重新实现 forEach
,如下所示。请注意,asyncForEach
本身会返回一个 Promise,因此您需要使用 .then()
来继续您的程序。
const asyncForEach = async (array, callback) => {
try {
for (let i = 0; i < array.length; i++) {
await callback(array[i]);
}
}
catch (ex) {
// handle exception here.
}
}
asyncForEach(array, async () => {
let bom = await BOMChild.findOne({
where: { id: e.id },
});
if (bom.BOMProductId || bom.BOMProductId === 0) {
throw {
name: " error",
description: `Description `,
};
}
}).then(() => {
// continue program.
});
如果您想使用更简洁但更令人困惑的解决方案来测试您的 Promise,请查看 Promise.all()
。
关于Javascript forEach 吞咽异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61667179/