简体   繁体   中英

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/

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.

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?

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. Event Loop Tutorial Webinar

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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