“This is the 18th day of my participation in the Gwen Challenge in November. See details: The Last Gwen Challenge in 2021.”

Let’s start with some code to see the output

Const test = async() => {console.log('async internal start'); await new Promise((resolve, reject) => { setTimeout(() => { console.log('setTimeOut'); Resolve ()},1000)}) console.log('async internal end'); } (async() => { console.log('start'); await test() console.log('end'); })() Guess what the output is? What about this one? Const test = async() => {console.log('async internal start'); await new Promise((resolve, reject) => { setTimeout(() => { console.log('setTimeOut'); Resolve ()},1000)}) console.log('async internal end'); } console.log('start'); test() console.log('end');Copy the code

Hold your horses, we’ll get the output later.

Async functions are syntactic sugar for Generator.

Since it's grammar sugar, there's got to be something better. 1) It is more semantic and await the completion of the following operation. 2) More applicability, Generator functions can only be followed by thunk functions or Promise objects. But await is different and can also be synchronized with code (equivalent to synchronous operations). 3) Generator returns an iteration while Async returns a promise. Const test = async() => {console.log('async internal start'); await console.log(1); The console. The log (' async internal end '); } console.log('start'); test() console.log('end'); Guess what this code says?Copy the code

Note:

Await can only be placed inside async functionsCopy the code

For multiple await statements in a function, there are a few things to consider

1) Are there dependencies between these asynchronous operations? If no, use concurrency. Map,foreach, promise.all(not really recommendation, because A error GG, you can use promise.allsettled () instead, you can verify map,foreach is not conqueued) : Await B... 2) Write all 'await' code into a try{} statement, otherwise an 'await' is returned, while 'await' can be followed by a 'capture'.Copy the code

In actual combat

Interviewer: What happens when you fail to request data from the back end? Sometimes this failure may not be an interface problem, but some other factors interfere. Me: prompt user data request error, try again. Interviewer: Emm.. Can you implement a request error and request again until a certain number of times after the request is still not successful again error? Oh, just use the for loop. for(let i = 0; i<3; i++){ try { await XXXX; break }catch(err) { console.log(err); } console.log(i); }Copy the code

If the request fails, the error is captured and the next request is made. The request exits the loop on success.