使用async / await时,如果一个调用出错,如何停止执行函数?

时间:2017-07-02 11:46:37

标签: javascript async-await

让我们想象一下我们有这样的功能:

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)
})

如果任何函数调用并不意味着在每次函数调用或使用回调后添加另一个语句,是否有更简单的方法来停止执行函数?

1 个答案:

答案 0 :(得分:3)

您只需使用try-catch

即可
Router.get('/', async function (req, res, next) {
  try { 
    let result = await someFunction()
    someOtherCall()
  }
  catch(exception) {
    next(exception)
  }
})