【问题标题】:Handle errors in async/await properly正确处理异步/等待中的错误
【发布时间】:2018-11-12 02:02:50
【问题描述】:

根据我的阅读,使用try/catch 是在使用async/await 时处理错误的“正确”方式。但是,如果我将请求的响应放在 try/catch 块中,我在尝试使用请求的响应时遇到了问题:

    try {
        async someMethod () {
            const result = await someRequest()
        }
    } catch (error) {
        console.log(error)
    }

    console.log(result) // cannot access `result` because it is not defined... 

因此,有没有更好的方法来处理错误并能够访问来自async/await 调用的请求响应?我能想到的唯一另一种方法是将整个代码块放在try/catch 块内..但我觉得有一种更优雅的方式..

提前致谢!

【问题讨论】:

  • try..catch 应该在 await 语句周围,而不是在函数定义周围。
  • 您发布的是Uncaught SyntaxError: Unexpected identifier。请发布有效的语法,否则我们无法为您提供帮助。

标签: javascript node.js error-handling async-await


【解决方案1】:
(async () => {
  result = null;
  async someMethod(){
    result = await someRequest();
  }
  console.log(result)
})()
.catch(error => console.log(error));

【讨论】:

    【解决方案2】:

    您应该在块范围之外声明变量,或者不要在结果前面使用任何关键字。这样,它将使其成为全局变量,您可以在块代码之外访问它。你可以这样写:-

    try {
        async someMethod () {
            result = await someRequest()
        }
    } catch (error) {
        console.log(error)
    }
    
    console.log(result)
    

    或者您也可以使用更短的方法而不是 try catch 以使代码更清晰,并且您还可以知道错误来自哪里。

    async someMethod () {
            result = await someRequest().catch(err=>{
                console.log(err)
            })
    }
    console.log(result)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-29
      • 2022-01-09
      • 2018-04-06
      • 2018-07-19
      • 2017-05-25
      • 1970-01-01
      • 2020-06-29
      • 2020-05-24
      相关资源
      最近更新 更多