简体   繁体   English

使用异步/等待时,当一个调用出错时如何停止执行功能?

[英]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.

相关问题 使用异步等待时,如何指定回调? - When using async await, how do you specify a callback? 当您忘记在 Javascript 中“等待”一个异步函数时如何发出警告? - How to warn when you forget to `await` an async function in Javascript? 当你不关心错误时,等待和异步 - await & async when you don't care about errors 当异步函数等待表达式“暂停”执行时,“暂停”是什么意思? - What is meant by 'pause' when async function await expression 'pauses' execution? 如果异步函数返回任何错误,如何停止执行下一条语句? - How to stop execution of next Statements if an Async function returns any errors? 如何在 Javascript 中停止/等待异步 function 的执行以避免错误? - How to stop/wait for the execution of an Async function in Javascript to avoid errors? 如何在Javascript中异步调用函数,以便我们可以在超时后处理其回调并停止执行? - How to call a function asynchronously in Javascript so that we can handle its callback and stop its execution when the time is out? 在异步等待函数中引发错误后停止执行代码 - Stop Execution of Code After Error thrown in Async Await function async / await 链接何时停止? - When does the async / await chaining stop? 在等待时出错,该等待仅在使用异步函数时对异步函数有效 - Getting error on await, that await is valid only on async function when using async function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM