[英]When using async/await, how do you stop execution of a function when one call errors out?
Lets imagine we have a function as so: 假设我们有一个这样的函数:
Router.get('/', async function (req, res, next) {
let result = await someFunction().catch(next)
someOtherCall()
})
If this errors out, it continues on to the global error handler by calling next(error_reason)
. 如果出现此错误,则通过调用
next(error_reason)
继续执行全局错误处理程序。 However, if the someFunction()
fails, we don't want someOtherCall()
to run at all. 但是,如果
someFunction()
失败,我们不希望someOtherCall()
在所有运行。 At the moment, I can see two ways of fixing this: 目前,我可以看到两种解决方法:
// Suggestion from https://stackoverflow.com/q/28835780/3832377
Router.get('/', async function (req, res, next) {
let result = await someFunction().catch(next)
if (!result) return // Ugly, especially if we have to run it after every call.
someOtherCall()
})
Router.get('/', async function (req, res, next) {
let result = someFunction().then(() => {
// Much less work, but gets us back to using callbacks, which async/await were
// meant to help fix for us.
someOtherCall()
}).catch(next)
})
Is there a simpler way to stop a function from executing if any of the functions call that doesn't mean adding another statement after every function call or using callbacks? 如果有任何函数调用不等于在每个函数调用后添加另一个语句或使用回调,是否有更简单的方法来阻止函数执行?
You can simply use try-catch
: 您可以简单地使用
try-catch
:
Router.get('/', async function (req, res, next) {
try {
let result = await someFunction()
someOtherCall()
}
catch(exception) {
next(exception)
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.