async 简单总结

async 异步操作,Generator的语法糖

async形式上的表现
    async function helloAsync(){
      return "helloAsync";
    }
    console.log(helloAsync()) // -->Promise { 'helloAsync' } 返回一个promise对象
复制代码
因为上面返回一个promise对象,所以可以使用then*/
    async function helloAsync(){
      return "helloAsync";
    }
    helloAsync().then(v=>{
      console.log(v);//--> "helloAsync"
    })
复制代码

await关键字(像yield)

    function awaitDemo(){
      return new Promise((resolve) => {  //promise 可以理解成一个放异步操作的容器
        seTimeout(function(){
          console.log("await");
          resolve();
        },100)
      })
    }
    async function helloAsync(){
      await awaitDemo();
      console.log("helloAsync");
    }

    helloAsync();
复制代码
1.awaitDemo() 返回一个promise对象
2.helloasync() 中 await awaitDemo();表示在这里要等待异步操作完成才会执行console.log;
3. 执行结果:await
       helloAsync
复制代码
4.既然是返回promise对象,所以可以返回rejected,如果返回rejected 那么console.log("helloAsync");就不会执行了
    function awaitDemo(){
      	return Promise.reject("error");
     }
      async function helloAsync(){
      	await awaitDemo();
      	console.log("helloAsync");//没有打印
      }
      helloAsync().then(v=>{
          console.log(v);
      }).catch(e=>{
         console.log(e);//"error"
      });
复制代码
await补充:await后可以是str,boolean,num,非异步func
    function awaitDemo2(){
      	setTimeout(function(){
              	console.log("await2");
              }, 100);
      	}
      async function helloAsync(){
      	await awaitDemo2();
      	console.log("helloAsync");
      }
      helloAsync(); //--->helloAsync
                    //    await2 不再等待setTimeout,所以先打印helloAsync
复制代码

应用:主要是顺序执行异步操作,确保每一步进行完再继续

      function one(){
       	   return new Promise((resolve) => {
               setTimeout(function(){
                 console.log("one");
                 resolve();
             },500)
           });
       } 

       function two(){
            return new Promise((resolve) => {
               setTimeout(function(){
                 console.log("two");
                 resolve();
             },500)
           });
       }
       function three(){
            return new Promise((resolve) => {
               setTimeout(function(){
                 console.log("three");
                 resolve();
             },500)
           });
       }
       function four(){
            return new Promise((resolve) => {
               setTimeout(function(){
                 console.log("four");
                 resolve();
             },500)
           });
       }
       async function task(){
       	console.log("start task");
      	await one();
      	await two();
      	await three();
      	await four();
      	console.log("end task");
      }
      task();
复制代码

转载于:https://juejin.im/post/5bfdf0dae51d4530db54161d

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值