没有得到下面 JavaScript 脚本代码中发生的事情

Not getting what's happening in the JavaScript script code below

async function async1(){
  console.log(1)
  await async2()
  console.log(2)
}

async function async2(){
  console.log(3)
}

console.log(4)

setTimeout(function(){
  console.log(5)
}, 0)

async1()

new Promise(function(resolve){
  console.log(6)
  resolve()
}).then(function(){
  console.log(7)
})

console.log(8)

4
1
3
6
8
7
2
5

请解释此代码如何创建上述输出。我对为什么 2 不在 log(3) 之后立即出现感到困惑。在我们使用 async await 之后到底发生了什么? 请对此提供一些见解。

由于您没有在 async1 方法调用 (async1()) 上执行 await,控件将在当前执行上下文中并且 console.log(2) 将移动到 micro task queue 在事件循环中。

请在浏览器控制台中更改 await async2() 再次执行您的代码,您会注意到预期的顺序。

更新:添加更多详细信息

async 实现了 return 承诺。 当使用 await 作为异步函数执行方式时,await 之后的剩余代码将在 async promise resolve 之后执行。

为了查看执行流程,我已经转换为直接使用 promises 的等效代码。

console.log(4);

setTimeout(function () { // move to call back queue
  console.log(5);
}, 0);

new Promise(function () {
  console.log(1);
  new Promise(function (resolve) {
    console.log(3);
    resolve();
  }).then(function () { // move to micro task queue
    console.log(2);
  });
});

new Promise(function (resolve) {
  console.log(6);
  resolve();
}).then(function () { // move to micro task queue
  console.log(7);
});

console.log(8);