An overview of the

Async /await is the syntactic sugar of promise. Promise, every time we use await, the interpreter creates a Promise object and then puts the operations from the remaining async function into the then callback. That is, the code after async is equivalent to the code in promise.then, except for the code immediately following await which is equivalent to the code inside the Promise.

async () => {
  a = a + 1;
  await fn();
  console.log('2', a) ; }// ======= is equivalent to ======>
  new Promise(() = >{
     fn()
     }).then(() = >{
       a = a + 1;
       console.log('2', a);
       })
Copy the code

Async /await instead of using Promise directly:

The advantage is that you can write code more clearly and accurately by handling the then call chain.

The disadvantage is that abusing await can cause performance problems because await blocks code, and perhaps subsequent asynchronous code does not depend on the former but still needs to wait for the former to complete, causing the code to lose concurrency.

Non-major: 1. Execute async without await, it will execute immediately, return a Promise object, and never block subsequent statements. Generators implement generators inside await. Generators retain what was in the stack before await

The sample

var a = 0
var b = async () => {
  a = a + await 10
  console.log('2', a) / / - > '2' 10
  a = (await 10) + a
  console.log('3', a) / / - > '3' 20
}
b()
a++
console.log('1', a) / / - > '1' 1Output:1 1 2 10 3 20
Copy the code

If you’re wondering, take a look at Eventloop to explain how it works

First function b, before execution to await 10 variable a is zero, because await inside the generators, generators will be kept on the stack, so this time a = 0 is preserved Because await is asynchronous operations, Console. log(‘1’, a) is executed, and the asynchronous code is executed. I’m going to take the saved value and use it, a = 10 and then I’m going to execute the code normally