猿问

Javascript forEach 吞噬异常

我正在尝试使用javascript中带有回调的循环来循环一个数组。问题是,当我抛出一个异常时,它会给出forEachasync


(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


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

    }

}

我做错了什么,解决这个问题的可能方法是什么。


温温酱
浏览 187回答 1
1回答

天涯尽头无女友

遗憾的是,没有安全的方法来将回调与 结合使用。最简单的解决方案是以如下所示的方式重新实现。请注意,它本身会返回一个 promise,因此您需要使用 来继续您的程序。asyncforEachforEachasyncasyncForEach.then()const asyncForEach = async (array, callback) => {&nbsp; try {&nbsp; &nbsp; for (let i = 0; i < array.length; i++) {&nbsp; &nbsp; &nbsp; await callback(array[i]);&nbsp; &nbsp; }&nbsp; }&nbsp; catch (ex) {&nbsp; &nbsp; &nbsp;// handle exception here.&nbsp; }}asyncForEach(array, async () => {&nbsp; let bom = await BOMChild.findOne({&nbsp; &nbsp; where: { id: e.id },&nbsp; });&nbsp; if (bom.BOMProductId || bom.BOMProductId === 0) {&nbsp; &nbsp; throw {&nbsp; &nbsp; &nbsp; name: " error",&nbsp; &nbsp; &nbsp; description: `Description `,&nbsp; &nbsp; };&nbsp; }}).then(() => {&nbsp; // continue program.});如果您想使用更干净但更令人困惑的解决方案来测试您的承诺印章,请看一下.Promise.all()
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答