async 与 await

134 阅读1分钟

async 与 await

  • 作用: 能帮助我们把 异步代码, 写的和 同步代码一样
  function fn(){
     const p = new Promise(function(def, res){
        const timer = Math.floor(Math.random() * 3000) + 1500

        setTimeout(()=>{
           if(timer> 3000){
            res('网络申请失败,请重新申请')
           }else{
            def('申请成功,欢迎访问')
           }
        },timer)
        
     })

     return p

    }
   async function fun(){
    /**
     *    await 后边需要跟着 promise
     *    await 表示等到的意思, 执行到 fn()   虽然是异步的
     *    但是因为有 await 关键字, 此时不会往下继续执行, 
     *    而是等待 fn() 执行完毕, 在往下执行
    */
      let res1 = await fn()
         
     }
     fun()

async/await 的问题

  • 没有办法捕获到 错误, 只能接受 promise 的成功状态
  • 如果报错, 会中断程序执行

async/await 的问题 的 解决方法1: try...catch

  • 首次执行的时候 会走 try 这个分支, 如果这个位置有报错
  • 他会结束执行 try 分支, 然后走 catch 分支
  • 如果再运行 try 分支的时候, 没有报错, 那么 catch 不会运行
 async function fun (){
  try{
    let r1 = await fn()
    console.log(r1)
   }catch(error){
    console.log(error)
    console.log('如果失败了,就会执行这行代码')
   }

 }
 fun()