Question

I've been reading some NodeJs articles in order to understand its async nature during which I found this and really liked it Node.js, Doctor’s Offices and Fast Food Restaurants – Understanding Event-driven Programming

There is a thing called EventLoop that is FIFO based queue. They say when an async function gets hit, it gets put to EventLoop and will continue to get executed over there.

I am little confused here. For example it is said here:

In actuality, async functions like setTimeout and setInterval are pushed onto an queue known as the Event Loop.

and in the same article:

The Event Loop is a queue of callback functions. When an async function executes, the callback function is pushed into the queue. The JavaScript engine doesn't start processing the event loop until the code after an async function has executed.

But it is different than this image:

enter image description here

Let's look at the following example:

console.log("Hello,");
setTimeout(function(){console.log("World");},0);

So from what I understand from those different explanations,

  1. First one says function(){console.log("World");} part of the setTimeout() function, that is the callback, will be put in EventLoop. Once the setTimeout is done, it will execute the EventLoop as well.
  2. The other one says, the whole thing setTimeout(function(){console.log("World");},0); will be put the EventLoop and will get executed...

I am confused even more now. It should be something simple but I guess a good but simple explanation would be nice for me for the following questions:

  1. Which one of the aforementioned things is true?
  2. What is EventLoop? An analogy, a real thing with methods, objects, etc?
  3. If I would like to implement a similar thing as EventLoop from scratch, how would it look like simply? Perhaps some code would be nice to see.
Was it helpful?

Solution 2

I'm going to attempt to answer, based on MDN's little information regarding Event Loops. Note, this answer is strictly for JavaScript, not specifically for Node.

From the sound of it, the confusion is that your second quote should probably have been written more clearly, such as:

The Event Loop is a queue of callback functions. When an async function executes, the callback function is pushed into the queue. The JavaScript engine doesn't start continue processing the event loop until the code after an async function has executed.

If that's the case, then it's much more consistent. All callbacks, when they fire, are entered into a FIFO queue, and run sequentially. I.e., if one event is firing, the next one won't fire until the first one completes.

The MDN reference I linked to above even includes pseudo-code for the Event Loop:

while(queue.waitForMessage()){
    queue.processNextMessage();
}

Timers and intervals are defined as part of DOM in the HTML spec. I couldn't find any direct reference to "Message Loop" in my quick check of that spec.

OTHER TIPS

Just think of Node's event loop as the "main function" that loops on the client side (except Node is on the server side, and you don't technically need an event loop in your code, since it's event based :).

Think about each client that connects as a JS object that runs through your code again, in it's own address space, with it's own variables, but in the same exact process, and same exact CPU as the rest of your program (you can cluster this, but generally that's how it works out of the box).

Worker threads are what blocking I/O get segmented off into, and with plugins, you can even spread worker threads into different Node servers (File I/O, DB I/O, Network access, etc, all get put into worker threads).

How Node works

While the event you make gets put in a queue, when it's executed, it runs in the main event loop (kind of), but more importantly, the event itself is placed in the event loop (the trigger that will call it).

This is all part of the V8 engine (the event loop, that is). What makes Node so great is it lets hundreds of thousands of clients into the same loop, and isolates blocking I/O.

The main take away point of this is that: Node is always doing something if something needs to be done, always.

Where as with other frameworks, I/O blocks the execution of the rest of the code.

Blocking vs Non-Blocking I/O

Basically, almost anything you normally write will happen in the event loop, but not exactly. What's meant to happen is your code runs once, then it just plugs in events, and quits.

Does that make sense?

So, while your code is done running, any events you queued up, (including more of your code, for example) still resides in the event loop.

Node is very different from everything else, but that's a pretty good explanation to get you started.

I wrote a lot more details on Quora if you're interested... https://www.quora.com/How-good-is-Node-js

The 2nd explanation is bogus — there is no mechanism in JavaScript to automatically put "the whole" thing in the event loop. Your first understanding is correct, and you can picture the event queue as an array of callbacks. An "iteration" of the event loop executes the next callback in the queue and removes it. The callback is allowed to queue more callbacks, and so on.

The event loop also checks for outside events, such as network activity, user activity or timer-based events, and dispatches appropriate callbacks for those actions. For this reason, the event loop never exits, except when the application shuts down. If there is currently nothing to do, it merely waits for something to happen.

NodeJS Event loop based on LIBUV and LIBIO,Refer this link https://github.com/joyent/libuv

I am also not clear about this any way i know little bit,

Event loop:

step 1:I send a request to Nodejs means read file from database; BUT Database already in use(So place this request into event loop)

step 2:This time nodejs receive other request means socket request Note:DataBase operation only busy now,Not socket so its execute socket operation

step 3:Receive multiple request and place to Event Loop then execute based on I/O

I/O: example:

   someoFileperation(callback)
    {
          //callback message i am finished any other related process in event loop
           }

   Next process:
    someSocketOperation(calback)
        {
           //Callback message i am finished my socket operation any other related process in Event loop
              }     
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top