前端开发

async /await

2020-11-25  本文已影响0人  liuyeqing
一.同步语法,彻底消灭回调函数;
二.asnyc/await 和promise的关系

1、执行async函数,返回的是Promise对象
2、await相当于Promise的then
3、try...catch可捕获异常,代替了Promise的catch

!(async function(){
    const p1 = Promise.resolve(300);
    const data = await p1;//await 相当于 Promise then
    console.log('data',data);
  })()
!(async function(){
    const data1 = await 400; // await  Promise.resolve(400)
    console.log('data1',data1);
})()
!(async function(){
     const data2 = await fn(); 
     console.log('data2',data2);
})()
!(async function(){
  const p4 = Promise.reject('err1') //rejected 状态
  try{
       const res = await p4;
       console.log(res);
  } catch(ex){
       console.err(ex)   // try..catch 相当于 Promise catch
  }
})()
三、重要例子
async function async1( ){
      console.log("async1 start");// 2 重要
      await async2() // undefined
    /*** await 的后面,都可以看作是callback里的内容,即异步,
        类似,event loop,setTimeOut(cb1)
        setTimeOut(function(){console.log(’async1  end‘)})
        Promise.resolve().then(()=>{console.log("async1 end")})  **/
       console.log("async1 end") // 5
}
async function async2( ){
  console.log("async2");//3
}
console.log("script start") // 1
async1()
console.log("script end")//4
//同步代码执行完(event loop)

执行结果:
1.script start
2.async1 start
3.async2
4.script end
5.async1 end

上一篇 下一篇

猜你喜欢

热点阅读