【问题标题】:Some errors inside of async functions don't work properly异步函数内部的一些错误无法正常工作
【发布时间】:2018-10-08 07:47:46
【问题描述】:

我在使用异步函数时遇到了问题。我没有意识到 classList.add('') 是非法的。因此,当我在 Firefox 中运行我的代码时,它停止运行我的函数,但没有出现错误,因为它是异步的(Chrome 显示错误)。这很难追踪,因为在原始程序中,带有 classList.add 的函数是两个函数调用。这里发生了什么以及将来如何避免它(除了必须检查两个不同浏览器中的错误日志)? PS 奖金,如果你能解释为什么异步错误实际上并没有停止执行的原因。

async function error1(){
  console.log('Fn async error: before')
  let a=undefined
  a.b=1
  console.log('after')
}
async function error2(){
  console.log('Fn async noError: before')
  document.body.classList.add('')
  console.log('after')

}
function error3(){
  console.log('Fn: before')
  document.body.classList.add('')
  console.log('after')
}


//Stops execution of function but not program
//Throws an error in Chrome and Firefox
error1()
//Stops execution of function but not program
//Throws an error in Chrome but not Firefox
error2()
//Errors and stops program
error3()

【问题讨论】:

标签: javascript async-await


【解决方案1】:

您应该等待可以捕获可能错误的执行。这是因为从您的 async 块内部创建的承诺表现得像承诺应该表现的那样 - 如果出现任何错误,承诺将解析为 rejected 并将异常通过管道传递给您附加到 拒绝路径。

两种方式:

首先 - 将明确的 then 添加到您的承诺中:

    async function error1(){
      console.log('Fn async error: before')
      let a=undefined
      a.b=1
      console.log('after')
    }

    error1().catch( e => {
        console.log( 'error: ' + e);
    } );

第二 - 在await 周围创建一个try-catch

async function error1(){
  console.log('Fn async error: before')
  let a=undefined
  a.b=1
  console.log('after')
}

(async function() {
   try {
      await error1();  
   }
   catch (e) {
       console.log( 'error: ' + e);
   }
}());

【讨论】:

  • 好的,但为什么 Firefox 在第二个示例中甚至没有显示错误?同样在我的原始代码中,我确实有等待,但如果错误没有像使用非异步函数那样停止执行,这对我来说似乎违反直觉。
  • 如果不使用 await 则不定义不同语句的执行顺序。不使用 await 调用 async 函数之后的语句将在 async 函数执行时甚至之前执行。
猜你喜欢
  • 2019-11-21
  • 2020-11-08
  • 2019-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多