【问题标题】:When using async/await, how do you stop execution of a function when one call errors out?使用 async/await 时,如何在调用出错时停止执行函数?
【发布时间】: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,或者函数出错时抛出。

标签: javascript async-await


【解决方案1】:

你可以简单地使用try-catch:

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

【讨论】:

    猜你喜欢
    • 2015-05-04
    • 2019-09-15
    • 2020-08-13
    • 1970-01-01
    • 2017-12-17
    • 1970-01-01
    相关资源
    最近更新 更多