宏任务 微任务

new Promise(function (resolve, reject) {
  console.log("AAAA"); 
  resolve();
}).then(function () {
  new Promise(function (resolve, reject) {
    console.log("BBBB"); 
    resolve();
  }).then(function () {
    console.log("CCCC") 
  }).then(function () {
    new Promise(function (resolve, reject) {
      console.log("DDDD") 
      resolve()
    }).then(function () {
      console.log("EEEE") 
    }).then(function() {
      console.log("FFFF") 
    })
    console.log("GGGG") 
  })
  console.log("HHHH")
}).then(function() {
  console.log("IIII")
})

new Promise(function (resolve, reject) {
  console.log("JJJJ");
  resolve()
}).then(function () {
  console.log("KKKK");
}).then(function (resolve, reject) {
  console.log("LLLL");
})

解析:
首先确认一下宏任务与微任务的概念:
宏任务,一般我们在调用栈中依次执行的回调函数都是以宏任务的形式依次同步执行。
微任务,当我们执行某些宏任务时,当前任务上还有其他支线任务作为回调等待当前任务执行完后再执行,大多数情况下这些任务会进入消息队列等待当前调用栈中的宏任务都执行完,作为下一轮的宏任务等待执行。而部分任务比较特殊,他不会等到下一轮执行,他会在当前一轮主任务执行完之后优先于下一轮宏任务来执行,这就是微任务。

new Promise(function (resolve, reject) { // p1
  console.log("AAAA"); 
  resolve();
}).then(function () { //then1
  new Promise(function (resolve, reject) { //p3
    console.log("BBBB"); 
    resolve();
  }).then(function () { //then3
    console.log("CCCC") 
  }).then(function () { // then6
    new Promise(function (resolve, reject) { //p4
      console.log("DDDD") 
      resolve()
    }).then(function () { //then7
      console.log("EEEE") 
    }).then(function() { //then8
      console.log("FFFF") 
    })
    console.log("GGGG") 
  })
  console.log("HHHH")
}).then(function() { //then4
  console.log("IIII")
})

new Promise(function (resolve, reject) { //p2
  console.log("JJJJ");
  resolve()
}).then(function () { //then2
  console.log("KKKK");
}).then(function (resolve, reject) { //then5
  console.log("LLLL");
})

/**
 * 首轮执行:执行p1打印AAAA => then1回调作为微任务进入等待 => 执行p2打印JJJJ => then2回调作为微任务进入等待。 微任务等待队列:then1,then2。
 * 第二轮执行:执行then1回调,执行p3打印BBBB,打印HHHH => then3回调作为微任务进入等待 => then4回调作为微任务进入等待 => 执行then2打印KKKK => then5回调作为微任务进入等待。 微任务等待队列:then3,then4,then5。
 * 第三轮执行:执行then3回调打印CCCC => 执行then4回调打印IIII,then6回调作为微任务进入等待 => 执行then5打印LLLL。微任务等待队列:then3
 * 第四轮执行:执行then3回调执行p4打印DDDD 打印GGGG,then7回调作为微任务进入等待。微任务等待队列:then7
 * 第五轮执行:执行then7回调打印EEEE,then8回调作为微任务进入等待。微任务等待队列:then8
 * 第六轮执行:执行then8回调打印FFFF
 */

打印结果:


image.png
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容