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

问题描述 投票:0回答:1

我正在使用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";
    }
}
javascript node.js asynchronous async-await try-catch
1个回答
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";
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.