抛出异步方法时未捕获到错误

时间:2020-06-09 11:56:00

标签: javascript node.js asynchronous async-await try-catch

当引发错误时,我正在使用async-await并通过try-catch处理错误。method3()未在method1()中捕获。但是,如果我删除了异步。 method2()foreach我能够捕获method1()中的错误!但是,如果我在foreach中删除异步操作,则无法使用await,因此无法使用await!有没有办法解决这个问题

class A {
    async method1(A, B) {
        return new Promise(async (resolve, reject) => {
            try {
                await this.method2(A, B);

            } catch (error) {
                console.log(error, "error")

            };
        });

    }
    async  method2(A, B, C) {

        await somethingelsecalled();
        Array.forEach(async (segment, index) => {
            result = await somethingcalled()
            this.method3(result);

        });
    }

    method3() {
        throw "error";
    }
}

1 个答案:

答案 0 :(得分:1)

用for循环代替foreach解决了问题

    class A {
        async method1(A, B) {
            return new Promise(async (resolve, reject) => {
                try {
                    await this.method2(A, B);

                } catch (error) {
                    console.log(error, "error")

                };
            });

        }
        async  method2(A, B, C) {

            await somethingelsecalled();
             for (const [index, segment] of Array.entries()) {
                result = await somethingcalled()
                this.method3(result);

            });
        }

        method3() {
            throw "error";
        }
    }