Before we get into the body, let’s first look at a piece of code. What does this code output?

let x = 0;

async function test() {
    x += await 2;
    console.log(x);	// Output what?
}

test();
x = 1;
Copy the code

The output 3? Or 2? The correct answer is: 2

If you know why 2 is printed, don’t continue reading this article; But if you clear up the reasons for this, then you can follow my analysis:

  1. Just because a function is declared asynchronously does not mean that all the code inside the function is executed asynchronously. In layman’s terms, the code inside an asynchronous function is executed synchronously until the first await expression appears, so let’s keep this in mind

  2. So what code is executed synchronously inside the test function? First we can change the form of the line x += await 2 slightly to: X = x + await 2, the x on the right side of the expression is a value operation and is executed synchronously, so when we get to await, the x on the right side of the expression has been evaluated and replaced with the value 0, and then the line x = 1 outside the test function is executed. X += await 2 equals x = 0 + await 2, so the final output is: 2

Now let’s make a slight change to the above code:

let x = 0;

async function test() {
    x = (await 2) + x;// put await before x
    console.log(x);	 // What is output here?
}

test();
x = 1;
Copy the code

If you understand what I said earlier, then I think you can give the correct answer, which is output: 3. The reason is: “Await 2” is being placed before the x expression this time, so the x operation is performed asynchronously, that is, x = 1 will be performed first, and then the x operation in the test function will be performed. Since the x in the test function forms a closure, So x = (await 2) + x equals x = (await 2) + 1, so the final output: 3

conclusion

The key to the above code is the order in which the x operation in test and the x = 1 line are executed, so we can conclude that await blocks the execution of subsequent expressions in the same expression

The original link: https://www.guoyunfeng.com/2018/05/28/await/