提问者:小点点

在异步方法内部引发时未捕获错误


我正在使用async-await,并在抛入错误时通过try-catch处理错误。 method3()没有在method1()中捕获它。 中删除了异步。 method2()forach我能够捕获method1()中的错误! 但是如果我删除foreach中的异步,我就不能使用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个答案

匿名用户

用for of循环替换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";
        }
    }

相关问题