简体   繁体   English

为什么Node.js事件循环需要多个阶段?

[英]Why does the Node.js event loop require multiple phases?

Having read through dozens of articles and documents describing the Node.js event loop, such as the one provided by Node.js themselves: https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/ 阅读了许多描述Node.js事件循环的文章和文档,例如Node.js本身提供的文章和文档: https : //nodejs.org/en/docs/guides/event-loop-timers-and-nexttick /

I simply cannot wrap my head around this: WHY does the event loop require several phases, each with their own callback queues? 我根本无法解决这个问题:为什么事件循环需要几个阶段,每个阶段都有自己的回调队列?

All the documents and articles describe the phases of the loop in terms of "this phase does so and so and executes callbacks set with X or Y", but never really expound on WHY these separate queues are necessary in the first place. 所有文档和文章均以“该阶段如此执行并执行用X或Y设置的回调”来描述循环的各个阶段,但是从来没有真正解释过为什么这些单独的队列首先是必要的。

Why would the callbacks of a setTimeout() or setImmediate() or socket closings need to be executed at a different point than the polling phase where supposedly the vast majority of callbacks are executed? 为什么setTimeout()或setImmediate()或套接字关闭的回调需要在与轮询阶段不同的位置执行,而轮询阶段应该执行绝大多数的回调?

if the callback queue in the polling phase is exhausted before moving to the next phase anyway, why not just have one queue that is interrupted for whatever non-queue related actions are performed in the other phases? 如果轮询阶段中的回调队列已耗尽,而无论如何都移至下一阶段,为什么不让一个队列因在其他阶段执行的任何与队列无关的操作而中断?

Probably this video link describes better than anyother material about callback . 该视频链接可能比其他有关回调的材料描述得更好。 To answer about different phases take this example and try to simulate according to the official document link to have a better picture. 为了回答有关不同阶段的问题,请以本示例为例,并尝试根据官方文档链接进行仿真以得到更好的画面。

setTimeout(function(){
        console.log("the first block after 3 sec.");
},3000);
console.log("Hello after 3000");
setTimeout(function(){
        console.log("the second block after 1 sec.");
},1000);
console.log("Hello after 1000");
setTimeout(function(){
        console.log("the third block after 2 sec.");
},2000);
console.log("Hello after 2000");
setTimeout(function(){
        console.log("the last block after 0 sec.");
},0);
console.log("End after 0");

Watch this video to understand the basic and confusing concept of the event loop in nodejs. 观看此视频,以了解nodejs中事件循环的基本概念和令人困惑的概念。 Event Loop Tutorial Webinar 事件循环教程网络研讨会

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM