async + await es7 concept is put forward, it is also to solve the problem of callback hell, it is only a syntactic sugar, essence, await
function is stillpromise,
It is noteworthy that, async
and await
must 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 promises
asynchronous 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/await
error handling can be tricky.
try…catch
Most standard (I recommend) is to use the try...catch
statement. When a await
time 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,)