async

2017-12-15  本文已影响39人  keknei

async是什么呢?大家都说他是异步请求的终极解决方案,这也证实了,async确实蛮吊的,下面我们看一下async的具体用法

async的基本用法

async函数有很明显的特征,就是函数前有async这个关键字,跟async陪套的是await,await在async函数里,async和await都返回一个promise的函数。

{
      function timeout(value,ms){
        return new Promise((resolve,reject)=>{
          setTimeout(()=>{
            resolve(value);
          },ms);
        });
      }

      async function asyncPrint(value,ms){
        const str=await timeout(value,ms);
        console.log(str);//hello world
        return str;
      };
      asyncPrint("hello world",2000).then(res=>{
        console.log(res);//hello world
      });
}

async的错误处理

  1. 第一种情况 单个await可以直接用try catch,不用then
function getImage(url){
    return new Promise((resolve,reject)=>{
        let img=new Image();
        img.src=url;
        img.onload=()=>{
            resolve("ok");
        };
        img.onerror=()=>{
            reject("err");
        };
        //错误的
        // setTimeout(()=>{
        //     show();
        // },0);
        //正确的
        show();
        console.log("执行");
    });
}

async function printImg(){
    try{
        const img=await getImage("http://pic4.nipic.com/20091217/3885730_124701000519_2.jpg");
        return img;
    }catch(e){
        console.log(e);// show is not defined
    }
    console.log("async执行");//async执行
}
printImg();
注意地方

这里需要注意一点的就是发生错误的地方必须在promise的上下文中,不然try catch捕捉不到这个错误,代码还是会报错,无法继续执行下面的代码

  1. 第二种就是用promise的all方法,因为all方法也是要么全部成功,要么一个失败就全失败,所以这种方法跟第一种比缺点是一样的
function getImage(url){
    return new Promise((resolve,reject)=>{
        let img=new Image();
        img.src=url;
        img.onload=()=>{
            resolve("ok");
        };
        img.onerror=()=>{
            reject("err");
        };
        show();
        console.log("执行");
    });
}

async function sPrintImg2(){
    Promise.all([getImage("http://pic4.nipic.com/20091217/3885730_124701000519_2.jpg"),getImage("http://pic4.nipic.com/20091217/3885730_124701000519_2.jpg")]).then(res=>
      console.log(res);
    ).catch(e=>
      console.log(e);//show is not defined
    );
}

sPrintImg2();
  1. 第三种就是麻烦了,对每个await用try catch抱起来,但是这种可以避免第一种或者第二种的缺点
function getImage(url){
    return new Promise((resolve,reject)=>{
        let img=new Image();
        img.src=url;
        img.onload=()=>{
            resolve("ok");
        };
        img.onerror=()=>{
            reject("err");
        };
        show();
        console.log("执行");
    });
}

async function sPrintImg3(){
    try{
        await getImage("http://pic4.nipic.com/20091217/3885730_124701000519_2.jpg");
    }catch(e){
        console.log(e);
    }

    try{
        await getImage("http://pic4.nipic.com/20091217/3885730_124701000519_2.jpg");
    }catch(e){
        console.log(e);
    }
    console.log("第三种方法async执行");
}

sPrintImg3();

还有一个值得注意的是,await必须在async函数的上下文中的。

{
let timeout=()=>{
    return new Promise((resolve,reject)=>{
        setTimeout(()=>{
            resolve("我是验证await必须放在上下文中");
        },100);
    });
}
//错误的
async function printTimeout(){
     setTimeout(()=>{
         const str=await timeout();
         return str;
     },0);//await is only valid in async function
}
//正确的
// async function printTimeout(){
//     const str=await timeout();
//     return str;
// }
printTimeout().then(res=>console.log(res));
}

如果await没有在async上下文中,就会报错,所以一定要注意这个地方

关于async await的就介绍这么多,希望对你有所帮助,如果想看更详细的资料,请狠狠的点击我

上一篇 下一篇

猜你喜欢

热点阅读