async + await personal understanding

async + await es7 concept is put forward, it is also to solve the problem of callback hell, it is only a syntactic sugar, essence, awaitfunction is stillpromise,

It is noteworthy that, asyncand awaitmust be used together.

Usage: first prepended function async This function is used to illustrate an asynchronous function

Then write the async await inside

E.g:

async function a(y){
    let sum = await b(3,4)
    let c= sum+y;
    console.log(c)
}
function b (x,y){
    return x+y;
}
a(10)

In the above example: sum variable is waiting for b () function is finished only value, in fact .then await and promise in the () almost

Using promisesasynchronous function has two possible return values: values resolved and rejected values. We can .then()be used for normal circumstances, .catch()for special cases. However, async/awaiterror handling can be tricky.

try…catch

Most standard (I recommend) is to use the try...catchstatement. When a awaittime of call, any value will be rejected as an exception is thrown.

E.g:

async function a(y){
 try{
  let a = await b(3,4)
    let c= a+y;
    console.log(c)
}catch(err){
	console.log(err);
 }
}
function b (x,y){
    return x+y;
}
a(10,)

 

 

Guess you like

Origin blog.csdn.net/weixin_41615439/article/details/88896675