Popey Gilbert Popey Gilbert - 5 months ago 28
Javascript Question

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)
. However, if the
someFunction()
fails, we don't want
someOtherCall()
to run at all. 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?

Answer Source

You can simply use try-catch:

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