如何在回调函数中停止外部函数的执行

3

让我们想象一下,我有一个这样的场景:

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

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

我希望只有异步函数成功运行时,console.log() 才会被执行。目前,我的解决方案是:

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')
}

但这不是很好。有没有不增加代码量的处理方法?类似于多个for循环:

outer: for (let i = 0; i < 10; i++) {
  for (let j = 0; j < 10; j++) {
    continue outer;
  }
  console.log('Never called')
}

只需使用then而不是catch吗?请看使用Async/Await的正确Try...Catch语法 - Bergi
2个回答

1
原来有更好的方法,你可以在catch函数内使用返回值:
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')
}

然而,这仍然不太好,不确定是否有更好的答案。

0

通常你会写成以下两种方式之一

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

或者

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

但这样并不是很好。有没有一种类似于多个for循环的处理方式?
是的,也可以使用一个代码块:
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')
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接