Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I stop execution of an outer function within a callback

Lets imagine I have a scenario like this:

async function some_func() {
  await some_query.catch(async (e) => {
    await some_error_code()
  })

  console.log('The above function ran without an error')
}

I only wish for the console.log() to be reached if the asynchronous function ran successfully. At the moment, my solution is:

async function some_func() {
  let did_error = false
  await some_query.catch(async (e) => {
    await some_error_code()
    did_error = true
  })

  if (did_error) return

  console.log('The above function ran without an error')
}

But that's not great. Is there any way of handling this without the added bulk? Similar to multiple for loops:

outer: for (let i = 0; i < 10; i++) {
  for (let j = 0; j < 10; j++) {
    continue outer;
  }
  console.log('Never called')
}
like image 316
Alexander Craggs Avatar asked Jan 19 '26 19:01

Alexander Craggs


1 Answers

Turns out there is a better way, you can use the return value within the catch function:

async function some_func() {
  let response = await some_query.catch(async (e) => {
    await some_error_code()
    return { err: 'some_error_code' }
  })

  if (response.err) return

  console.log('The above function ran without an error')
}

However this still isn't great, not sure if there's a better answer.

like image 163
Alexander Craggs Avatar answered Jan 21 '26 09:01

Alexander Craggs