• : Promise, async/await, process.nextTick
  • dom
  • macro task : including overall code script, setTimeout, setInterval
Micro tasks and macro tasks will enter different event queues. For example, setTimeout and setInterval will enter the same Event Queue.
In an event loop, first execute the queue of , then execute dom, and finally execute the queue of macro task

Execute immediately when encountering the console
First, you will encounter setTimeout and put it in the macro task event queue.
Then go back to promise, new promise will be executed immediately, then it will be distributed to microtasks
事件循环

console.log("1")
setTimeout(()=>{
    console.log("2")
})
new Promise((resolve) => {
   resolve()
   console.log("3")
}).then(()=>{
   console.log("4")
}).finally(()=>{
   console.log("5")
})
console.log("6")

output
1 3 6 4 5 2


second example

console.log("1");
setTimeout(() => {
  console.log("7");
  Promise.resolve().then(() => {
    console.log("9");
  });
  new Promise((resolve, reject) => {
    console.log("8");
    resolve("10");
    setTimeout(() => {
      console.log("14");
    })
  }).then((data) => {console.log(data)});
}); 
new Promise((resolve, reject) => {
  console.log("2");
  resolve("4");
  setTimeout(() => {
    console.log("11");
  })
}).then((data) => {
  console.log(data);
  setTimeout(() => {
    console.log("12");
  })
  Promise.resolve("5").then((d) => {
    console.log(d);
    Promise.resolve("6").then((d) => {
      console.log(d);
    });
  });
  setTimeout(() => {
    console.log("13");
  })
})
console.log("3");

output:

1 2 3 4 5 6 7 8 9 10 11 12

Schematic
事件循环示意图


aprildove
233 声望15 粉丝

一个前端


下一篇 »
position 属性