async与eventLoop结合分析

有错误的地方麻烦告知,谢谢!

async function test(){
  const a=await new Promise((resolve,reject)=>{
    console.log('开始执行b Promise')
    setTimeout(() => {
      console.log('a:1')
      resolve(1)
    }, 4);
  })
  console.log('async中的a得到结果了')
  const b=await new Promise((resolve,reject)=>{
    console.log('开始执行a Promise')
    setTimeout(() => {
      console.log('b:2')
      resolve(2)
    }, 4);
  })//相当于promise.then(val=>b=val),所以async里面的await是一个promise微任务
  console.log('async中的b得到结果了')
  return [a,b]
}
test().then(val=>{
  console.log(val)
})
console.log('hahaha...')
setTimeout(() => {
  console.log('hahaha2')
}, 4);
//node结果:(不用管)
//开始执行b Promise
//hahaha...
//a:1
//hahaha2
//async中的a得到结果了
//开始执行b Promise
//b:2
//async中的b得到结果了
//[ 1, 2 ]

//chrome结果:
//开始执行b Promise
//hahaha...
//a:1
//async中的a得到结果了
//开始执行b Promise
//hahaha2
//b:2
//async中的b得到结果了
//[1, 2]

解释:

  1. test函数内部首先类似于new Promise(<1>...).then(<2>val=>{const a=val ....}),因此先执行<1>中的同步任务,首先打印""开始执行a Promise",并且将setTimeout中回调函数注册(放入eventTable 1)并在4ms后(移入eventQueue)中 宏任务Queue 1 ,注册await(promise.then)后面的回调函数<2>(放入eventTable 2),注册test().then后面的回调函数(放入eventTable 3),继续执行同步任务,打印"hahaha...",将setTimeout中回调函数注册(放入eventTable 4)并在4ms后(移入eventQueue)中 宏任务Queue 2 ,同步操作结束,微任务Queue为空,所以第一轮事件循环结束;
  2. 第二轮事件循环开始,先执行宏任务Queue 1 ,打印"a:1",并且resolve了,此时将eventTable 2中的回调函数(移入eventQueue中)微任务Queue 1,同步操作结束后遍历微任务Queue,执行微任务Queue 1,给b赋值并打印"async中的a得到结果了",然后执行类似于new Promise(<3>...).then(<4>val=>{const b=val ...}),因此先执行<3>中的同步操作,打印"开始执行b Promise",将setTimeout中回调函数注册(放入eventTable 5)并在4ms后(移入eventQueue)中 宏任务Queue 3,注册await(promise.then)后面的回调函数(放入eventTable 6),第二轮事件循环结束;
  3. 第三轮事件循环开始,先执行宏任务Queue 2,打印"hahaha2",微任务Queue为空,所以第三轮事件循环结束;
  4. 第四轮事件循环开始,执行宏任务Queue 3,打印"b:2",并resolve了,此时将eventTable6中的回调函数(移入eventQueue中)微任务Queue 2,同步操作结束后遍历微任务Queue,执行微任务Queue 2,给b赋值并打印"async中的b得到结果了",并且resolve了,此时将eventTable3中的回调函数(移入eventQueue中)微任务Queue 3,执行微任务Queue 3,打印了"[1,2]",第四轮事件循环结束。

你可能感兴趣的:(async与eventLoop结合分析)