3

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')
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Alexander Craggs
  • 7,874
  • 4
  • 24
  • 46
  • Just use `then` instead of `catch`? Have a look at [Correct Try…Catch Syntax Using Async/Await](https://stackoverflow.com/q/44663864/1048572) – Bergi Dec 05 '17 at 09:35

2 Answers2

1

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.

Alexander Craggs
  • 7,874
  • 4
  • 24
  • 46
0

You would usually write either

function some_func() {
  return some_query().then(res => {
    console.log('The above function ran without an error')
  }, (e) => {
    return some_error_code()
  })
}

or

async function some_func() {
  try {
    await some_query()
  } catch(e) {
    await some_error_code()
    return
  }
  console.log('The above function ran without an error')
}

But that's not great. Is there any way of handling this similar to multiple for loops

Yes, it's also possible to use a block:

async function some_func() {
  noError: {
    try {
      await some_query()
    } catch(e) {
      await some_error_code()
      break noError
    }
    console.log('The above function ran without an error')
  }
  console.log('This will always run afterwards')
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375