关于javascript:js事件循环

  • 微工作:Promise,async/await,process.nextTick
  • dom
  • 宏工作:包含整体代码script,setTimeout,setInterval

微工作、宏工作会进入到不同的event queue。比方setTimeout和setInterval会进入雷同的Event Queue。
在一个event loop,先执行微工作的queue,在执行dom,最初宏工作的queue

遇到 console 立刻执行
首先会遇到setTimeout,将其放到宏工作event queue外面
而后回到 promise , new promise 会立刻执行, then会散发到微工作

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")

输入
1 3 6 4 5(dom)2


第二个例子

console.log(1);
setTimeout(() => {
  console.log(2);
  Promise.resolve().then(() => {
    console.log(3)
  });
}); 
new Promise((resolve, reject) => {
  console.log(4)
  resolve(5)
}).then((data) => {
  console.log(data);
}).then((data) => {
  console.log('another');
})
setTimeout(() => {
  console.log(6);
})
console.log(7);

输入:
1 4 7 5 another (dom) 2 3 6

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理