Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

关于 Node 的事件循环 版本v10 之前与 版本v11 之后 #13

Open
law-chain-hot opened this issue Mar 31, 2020 · 1 comment
Open

Comments

@law-chain-hot
Copy link
Owner

law-chain-hot commented Mar 31, 2020

关于 Node 的事件循环 版本v10 之前与 版本v11 之后

理解浏览器的事件循环不难,但是 Node 的事件循环涉及到版本问题,会稍微复杂一点

此外 setImmediate() 是在 check 阶段执行

v10 及其以前,事件循环为清空

  1. 清空当前阶段任务(比如 timer 就是 setTimeout等)
  2. 清空process.nextTick()
  3. 清空当前阶段产生的所有微任务

v11 及其以前,事件循环改为与浏览器一样

  1. 完成一个 当前阶段 宏任务
  2. 清空process.nextTick()
  3. 清空当前阶段产生的所有微任务
  4. 继续完成下一个 当前阶段 宏任务

image

分别在 Node v8 v11 v12 版本测试如下代码:

setTimeout(() => {
    let p = new Promise((resolve) => {
        console.log('p1');
        resolve('promise1')
    }).then((data) => console.log(data))


    process.nextTick(function () {
        console.log('nextTick1');
    })

}, 0)


setTimeout(() => {
    let p = new Promise((resolve) => {
        console.log('p2');
        resolve('promise2')
    }).then((data) => console.log(data))


    process.nextTick(function () {
        console.log('nextTick2');
    })
}, 0)

结果如下图

image

@law-chain-hot
Copy link
Owner Author

console.log(1);
setTimeout(() => {
  console.log(2);
});
process.nextTick(() => {
  console.log(3);
});
setImmediate(() => {
  console.log(4);
});
new Promise((resolve) => {
  console.log(5);
  resolve();
  console.log(6);
}).then(() => {
  console.log(7);
});
Promise.resolve().then(() => {
  console.log(8);
  process.nextTick(() => {
    console.log(9);
  });
});


// 1
// 5
// 6
// 3
// 7
// 8
// 9
// 2
// 4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant