async await

374 阅读1分钟

async 是Generator 的语法糖。

基础用法

//第一种
 async function fn(){
   await 'promise'
}
//第二种
const fn = async ()=>{
    await 'promise'
}

await

 async function fn(){
   await 'promise';
   // 1.await 后是promise 或者包含then方法的对象则直接返回
   // 2. await后是原始类型则会调用Promise.resolve 转成promise
}
//等价于
async function fn(){
    await Promise.resolve('promise')
}
promise then 的语法糖
const p = new Promise(resolve=>{
    console.log(3)
    resolve('p')
})

async function fn(){
    console.log(1)
    const str = await p;
    console.log(str)
    console.log(2)
}

//等价于
async function fn(){
    console.log(1)
    p().then(res=>
        console.log(res)
        console.log(2)
    })
}
//1,3,p,2
reject
const p = new Promise((resolve,reject)=>{
    reject('p')
})

async function fn(){
    await p;
    console.log(2) //reject时 这个不走
}

//1.错误会被fn catch捕获
fn().catch(err=>{
    //err p
})
//2. try{}catch
async function fn(){
    try{
        
        await p;
    }catch(err){
        
    }
    console.log(2) 
}

//3.提前捕获返回一个resolve(新的promise)
async function fn(){
    await p().catch(err=>resolve(err));
    console.log(2)
    //p 2
}

返回值Promise

 async function fn(){
   await 'promise';
   return 'value'
}

fn().then(res=>{
   // 所有的await 都执行完成,执行
   // res  value
}).catch(err=>{
    //1.捕获fn 错误
    //2.捕获await promise 的reject
})