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

时间:2017-12-05 07:51:10

标签: javascript node.js async-await

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

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

2 个答案:

答案 0 :(得分: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')
}

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

答案 1 :(得分: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')
}