About the async await

Async await was introduced in THE ES2017 standard and functions itself as a syntactic sugar shorthand.

Here’s an example of using promises:

 function myPromise(flag) {
     return new Promise((resolve, reject) = > {
         if (flag) {
             return resolve(flag)
         } else {
             return reject('error')}}}// call p2 on the callback from p1
 const p1 = myPromise(1)
 p1.then(v= > {
     const p2 = myPromise(2)
     p2.then(v= > {
         console.log(v)
     })
 })
Copy the code

Since p2’s arguments are related to the return value of P1, this example ensures that P2 will be called if P1’s promise is successful, ensuring the order of the calls. If only a few promises are required, the structure is not too complicated to implement. If multiple promises need to be called later, Then calling promises results in code that is too nested and unreadable.

The advent of async await solves the problem of code readability.

Here’s an example:

 function myPromise(flag) {
     return new Promise((resolve, reject) = > {
         if (flag) {
             return resolve(flag)
         } else {
             return reject('error')}}}// P1 can get the result of myPromise directly
 // let v
 const p1 = await myPromise(1)
 // p1.then(val => { v = val }) 
 const p2 = await myPromise(p1)
 // p2.then(val => { v = val })
 const p3 = await myPromise(p2)
 // p3.then(val => { v = val })
 const p4 = await myPromise(p3)
 // p4.then(val => { v = val })
 const p5 = await myPromise(p4)
 // p5.then(val => { v = val })
 const p6 = await myPromise(p5)
 // p6.then(val => { v = val })
 const p7 =  myPromise(p6)
Copy the code

This ensures that asynchronous methods are called in order without relying on extensive.then nesting.

Thinking about efficiency

PostData and getData seem to be a bit of a misunderstanding, as they are both supposed to be asynchronous functions and not really executable code.

Here is a piece of pseudocode:

 function getData(url) {
     return url
 }
 ​
 function postData(url) {
     console.log(url)
 }
 ​
 let data1 = await getData('/xxx') // Operation 1 takes 10s
 let data2 = await getData('/xxx') // Operation 2 takes 10s
 postData(data1 + '/xxx') // Operation 3 takes 20 seconds
 postData(data2 + '/yyy') // Operation 4 takes 5s
Copy the code

Those familiar with the JS event loop should be able to quickly calculate the time required to execute, a total of 40 seconds to execute, so can we optimize this pseudo-code? The answer is yes.

Let’s look at the optimized code:

 function getData(url) {
     return url
 }
 ​
 function postData(url) {
     console.log(url)
 }
 ​
 let data1 = await getData('/xxx') // Operation 1 takes 10s
 postData(data1 + '/xxx') // Operation 4 takes 20 seconds
 let data2 = await getData('/xxx') // Operation 2 takes 10s
 postData(data2 + '/yyy') // Operation 3 takes 5s
Copy the code

In this case, the execution time is optimized to 30s. Let’s look at the comparison of the two execution times:

The first way

The second way

Therefore, we should pay attention to the call order of asynchronous code when we use async await. Proper optimization can reduce the running time of the program, and we should use async await syntax sugar correctly. We need to await the asynchronous request only if subsequent operations need to use the data obtained from the asynchronous request. Otherwise, we do not need to await the asynchronous request.

subsequent

Although we may feel that this topic is more title party, but I did not want to in-depth analysis of the meaning, just want to exchange and discuss, hope that everyone’s comments or a little polite. There is something wrong with my understanding about the comment section. Here, I use setTimeout to control the return time of the Promise. The code is as follows

function t5s() {
    return new Promise((resolve, reject) = > {
        setTimeout(() = > {
            resolve(1)
            console.log('5s')},5000); })}function t3s() {
    return new Promise((resolve, reject) = > {
        setTimeout(() = > {
            resolve(1)
            console.log('3s')},3000); })}function t2s() {
    return new Promise((resolve, reject) = > {
        setTimeout(() = > {
            resolve(1)
            console.log('2s')},2000); })}/* Wait 5s to return the first Promise and print 5s, then wait 3s to return the second Promise and print 3s, and finally wait 2s to return the third Promise and print 2s, taking a total of 10s */
(async() = > {await t5s()
    await t3s()
    await t2s()
})()
/* Here my understanding is that the three operations will be executed successively in the microtask pool, so 2s prints 2s, 3s prints 3s, 5s prints 5s, and the total time is 5s */
(() = > {
    t5s()
    t3s()
    t2s()
})()
Copy the code