Using async and await the

async is actually the only ES7, is the evolution of asynchronous operation, in fact encapsulated object returns a Promise

  async function test(){
  	 	   return 1111
  	 }
  console.log(test())  //Promise {<resolved>: 1111}

async method before normal function plus "async" keywords. Implementation of this function, found 1111 and did not return, but by Promise.resolved) 1111 will become a Promise object returned package (. Since the object is returned Promise, then it may be treated with the method.

test().then(res=>{
  		console.log(res)  //1111
})  

the await
the yield keywords can only be used in the Generator function also, the await keyword can not be used alone, in need async method. await literally means "wait", which is waiting for the results in the back of the expression.

function testWait(){
  		return new Promise((resolve,reject)=>{
  			setTimeout(function(){
          	console.log("testWait");
          	resolve();
          }, 1000);
  		})
  	}
 async function test(){
  	 	    await testWait()
  	 	   console.log("hello");
 }
  	test()  // 依次打印出  testWait  hello

await the effect, that is the main function blocks execution until the function returns behind the Promise .

await not only behind only a Promise object may be a string, boolean, numeric and function of normal

function testWait(){
  			setTimeout(function(){
          	console.log("testWait");
          }, 1000);
  	}
  	 async function test(){
  	 	    await testWait()
  	 	   console.log("hello");
  	 }
  	test()  // 依次打印出 hello testWait

By way of example above we can see that
. 1, await later if the object is a Promise, await block the execution of the main function, waiting Promise resolve the object, and then resolve the value obtained as the calculation result await expressions, and then proceed to the main function the following code.
2, await later if the object is non-Promise, or directly the amount of the await wait function returns, instead of waiting for the execution result.

Scenarios
a complete cooking tasks need to be done step by step

	//洗菜
   function prepare(){
   	   return new Promise((resolve) => {
           setTimeout(function(){
             console.log("洗菜");
             resolve();
         },100)
       });  
   }
 
   //炒菜
   function fired(){
        return new Promise((resolve) => {
           setTimeout(function(){
             console.log("炒菜");
             resolve();
         },100)
       }); 
   }
 
   //吃饭
   function eat(){
        return new Promise((resolve) => {
           setTimeout(function(){
             console.log("吃饭");
             resolve();
         },100)
       });
   }
   async function task(){
   	console.log("开始准备");
  	await prepare();
  	await fired();
  	await eat();
  	console.log("完成");
  }
  task(); //依次打印出: 开始准备 洗菜 炒菜 吃饭 完成

Guess you like

Origin blog.csdn.net/smlljet/article/details/91958303