async/await捕获异常

792 阅读1分钟

try/catch

  • 既能捕获异步异常,也能捕获同步异常
  • 多个串行的异步可以使用一个try/catch捕获异常
  • 报错后后续代码不会执行,正常resolve才会执行

async function a(){
  try{
    const res=await Promise.reject('2333')
    console.log(666)
  }catch(err){
  	console.log(err)
  }
}

a()

// 2333

.catch()

  • 只能捕获一个异步异常
  • 抛出异常后后续代码继续执行

async function a(){
  const res=await Promise.reject('2333').catch(err){
  	console.log(err)
  }
  console.log(666)
 
}
a()
// 2333
// 666

重复尝试

function randomAjax() {
  return new Promise(((resolve, reject) => {
    Math.random() > 0.5 ? resolve() : reject();
  }))
}

async function polling(count) {
  for (let i = 0; i < count; i++) {
    try {
      const res = await randomAjax();
      break;
    } catch (err) {
    }
  }
}

// 重复尝试至多3次,成功跳出循环
polling(3)