【问题标题】:error is not being caught when throwing inside a async method抛出异步方法时未捕获错误
【发布时间】:2020-09-28 14:21:59
【问题描述】:

我正在使用 async-await 并在抛出错误时通过 try-catch 处理错误。method3() 它没有在 method1() 中捕获。但是,如果我删除了 async 中的。 method2() foreach 我能够捕捉到 method1() 中的错误!但是如果我在 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();
        Array.forEach(async (segment, index) => {
            result = await somethingcalled()
            this.method3(result);

        });
    }

    method3() {
        throw "error";
    }
}

【问题讨论】:

  • 请不要在这样的.forEach循环中使用async / await
  • 在 foreach 中是否可以使用 await?
  • for of 循环更好
  • 工作就像一个魅力!但是有什么解释为什么它不能在早期的方法中工作

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


【解决方案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";
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-01
    • 2015-04-16
    • 2017-10-23
    • 2020-01-28
    • 1970-01-01
    • 2013-05-07
    • 1970-01-01
    • 2019-06-10
    相关资源
    最近更新 更多