【发布时间】: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