New syntax in ES6 (7) — async… Await

Time:2021-7-29

What is async

Async means “asynchronous”. As the name suggests, async is a keyword related to asynchronous operations. Async is unique to ES7 and is closely related to promise and generator.

Use syntax:

async function name(param){

Param / / parameter name passed to the function

Statements / / function body

}

name().then(function(res){

RES / / results returned by asynchronous operations

})

The async function returns a promise object. You can use the then method to add a callback function. Specific examples are as follows:

async function show(){
 return {a:12,b:15}
}
console.log(show())//Promise {<fulfilled>: {…}}
show().then(res=>{
 console.log("res",res)
})

What is await

Await keyword exists in the async function expression. It is used to wait for promise object and pause execution. After the asynchronous operation is completed, resume the execution of async function and return the resolved value. If await is placed outside the asnyc function, a syntax error will be reported.

Use syntax:

asnyc function name(){

returnValue = await expression;

}

Expression is a promise object or a value to wait for. There are two processing methods for different expressions:

For promise objects, await blocks the execution of the main function. After the promise object executes resolve, the resolve return value is used as the operation result of await expression, and then continue to execute downward.

For non promise objects, they can be strings, Boolean values, numeric values, ordinary functions, and so on. Await returns the corresponding value directly instead of waiting for its execution result.

Await waits for promise object instances as follows:

async function test1(){
 Console.log ("execute")
 return new Promise((resolve,reject)=>{
  setTimeout(()=>{
   Console.log ("success returned after 3 seconds delay")
   resolve({a:'1'})
  },3000)
 })  
}
async function test2(){
 let x = await test1()
 console.log("x",x)//{a: "1"}
 return x
}
test2().then(function(res){
  console.log("res",res)//{a: "1"}
})

Examples of await and ordinary functions are as follows:

function test3(){
 Console.log ("normal function")
}
async function test4(){
 await test3()
 Console.log ("direct execution")
}
test4()

Catch exception

The above await is followed by the promise object. We know that the promise has two states, resolved () and rejected (). If the promise object becomes rejected, how will it be handled?

function testAwait(){
 return Promise.reject("error");
}
async function test1(){
 await testAwait();
 console.log("test1");// No printing
}
test1().then(v=>{
 console.log(v);
}).catch(e=>{
 console.log(e);//"error"
})

From the execution results of the above instance, it is found that the returned reject state is captured by the outer catch, and then the subsequent execution is terminated. However, in some cases, even if an error occurs, we continue to execute rather than interrupt. At this time, we catch the inner exception with the help of try… Catch.

function test1(){
 return new Promise((resolve,reject)=>{
 reject("error")
 })
}
async function test2(){
 try{
  await test1()
 }catch(e){
  Console.log ("error report", e)
 }
}
test2().then((res)=>{
 Console.log ("execute successfully", RES) // print: execute successfully, undefined
}).catch(err=>{
 console.log('err',err)
})

Comparison between generator and async:

  • Async uses the await blocking principle to replace the yield of the generator.
  • Compared with async, the generator does not need the run process function and perfectly implements the asynchronous process.

From promise to generator to async, the solution for asynchronous programming is becoming more and more perfect, which is the charm of ES6’s continuous development.