• Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

This is the first article I wrote to share knowledge, and I will share some of my own dry goods in the future. Due to my limited experience, there may be a lot of deficiencies, but I still hope to help you in the same effort, come on together

We all know that async and await are used together, but why is it that sometimes async and await cannot achieve the desired synchronization effect? Please read on to solve some of your doubts.

  • Let’s start with a very basic example of using async and await:
function testAwait(){
    return new Promise((resolve, reject) = >{
        setTimeout(() = >{
            resolve(123)},3000)})}async function testAsync(){
    let n = await testAwait()
    console.log(n)
}
testAsync()
Copy the code

The code above will print 123 after 3 seconds. Note that if you want to wait 3 seconds before performing a testAwait operation, you can return a new Promise in the testAwait function, and await returns a Promise object. Note that return is required.

  • If you do not use return, then await must be followed by an async function, which could also be written as follows:
async function testAwait(){
   await new Promise((resolve, reject) = >{
        setTimeout(() = >{
            console.log(111)
            resolve()
        },3000)})}async function testAsync(){
    await testAwait()
    console.log(222)
}
testAsync()
Copy the code

The above code can still achieve the desired effect, the code execution result is: after 3 seconds to print 111 and 222. Therefore, when we use async and await, we only need to pay attention to these two points, and basically there will be no problems. Of course, we also need to remember the important exception handling.

That’s all for this little share. I’ll see you next time. Bye