async 简单总结

189 阅读1分钟

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();