async, await how to use

async declare a function is asynchronous, it awaits for waiting for the asynchronous and await only in the async.

Use async, await parallel processing request, half speed:

The plurality promise to make requests directly to async functions performed, and then await operation.

 1 async function asyncAwaitfun(str){
 2   return await new Promise((resolve, reject)=>{
 3     setTimeout(()=>{
 4     resolve(str)
 5     },1000)
 6   })  
 7 }
 8 
 9 const parallel = async()=>{
10   const parallelOne = async(asyncAwaitfun('string 1'))
11   const parallelTwo = async(asyncAwaitfun('string 2'))
12 
13   console.log(async parallelOne)
14   console.log(async parallelTwo)
15 }

async, await error handling:

When the asynchronous request fails, i.e. the object to be processed Promise returns reject state;

Among the promise reject the request can be used when the catch, in order to maintain robustness of the code, using the async, the await time, we use the try catch to handle errors;

. 1  the async function catchErr () {
 2    the try {
 . 3     const RES = the await the GetData () // Request Interface background 
. 4      IF (res.code == 200 is ) {
 . 5       the console.log ( ' success ' )
 . 6      }
 . 7   }
 . 8    the catch ( ERR) {
 . 9      the console.log (ERR)
 10    }
 . 11 }

 

Guess you like

Origin www.cnblogs.com/lesliejavascript/p/11014802.html