Javascript forEach 吞咽异常

Javascript forEach swallowing exceptions

我正在尝试使用 forEach 循环和 javascript 中的 async 回调来遍历数组。问题是当我抛出异常时它给出

(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 块。这是我的代码

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 本身 returns 是一个承诺,因此您需要使用 .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()