在 Node JS 中展示 setImmediate 函数功能的常见示例是以下代码
console.log('1');
setImmediate(() => console.log('2'));
console.log('3');
计算结果为
1
3
2
据我所知,setImmediate 回调是在事件循环的 check
阶段执行的
但是我不明白获取新的顺序指令适合哪里?我们是否可以保证 Node 在执行检查阶段之前获取并执行 console.log('3')
,从而在 2
之前打印 3
?如果是这样 - 在到达 check
阶段之前 Node 将执行多少条这样的指令?
最佳答案
However I don't understand where fetching new, sequential instruction fits there?
无需获取任何新内容,因为所有指令都必须在此时加载,因为我们已经在执行它们了!
- 确定您的代码应该运行
- 您的代码(全部 3 行)运行
- 进入事件循环并检查还有什么要做
- 确定回调应该运行
- 回调(所有“1 行”)运行
- ...
Are we guaranteed that Node will fetch and execute console.log('3') BEFORE executing the check phase and therefore print 3 before 2?
是的。
If so - how many such instruction would Node execute before reaching check phase?
无穷多个。
JavaScript 是单线程*,没有任何东西可以抢占您的代码(除了 Ctrl+C)。
因此,以下代码将永远输出 3
并且永远不会到达 2
**:
console.log('1');
setImmediate(() => console.log('2'));
while (true) {
console.log('3');
}
1
3
3
3
3
... (forever)
同样,以下代码将永远打印 2A
并且永远不会到达 2B
:
console.log('1');
setImmediate(() => {
while (true) {
console.log('2A');
}
});
setImmediate(() => console.log('2B'));
console.log('3');
1
3
2A
2A
2A
2A
... (forever)
(如果您要将 setImmediate(() => console.log('2B'));
移至第一个回调内部而不是将其放在其下方,则同样适用。)
*:是的,node.js 中存在工作线程,浏览器中存在服务工作线程,但它们存在于自己的环境中。
**:...在此过程中消耗 100% 的一个 CPU 核心,并且不对任何事件或信号使用react,因此仅将此视为学术兴趣的示例,而不是您在实际代码中编写的内容.
关于javascript - 这个例子中Node的执行顺序是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62085685/