【发布时间】:2017-07-02 11:46:36
【问题描述】:
假设我们有这样一个函数:
Router.get('/', async function (req, res, next) {
let result = await someFunction().catch(next)
someOtherCall()
})
如果出错,它会通过调用next(error_reason) 继续处理全局错误处理程序。但是,如果someFunction() 失败,我们根本不希望someOtherCall() 运行。目前,我可以看到两种解决方法:
// 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)
})
如果任何函数调用并不意味着在每个函数调用后添加另一个语句或使用回调,是否有更简单的方法来阻止函数执行?
【问题讨论】:
-
为什么不使用 Promise 来实现这一点
-
@Volem 我们使用的是promise,someFunction()返回一个promise,当函数运行成功时resolve,或者函数出错时抛出。