Skip to content Skip to sidebar Skip to footer

What Is The Exact Handling Of The Nodejs Event Loop?

I know that NodeJS Event Loop collects Tasks from Event Queue and transfers control to the callback of the Task. When the task is completed, the Task transfers control from Event L

Solution 1:

You can think of the Event Loop as an actual loop, something like:

let event_queue = [compiled_toplevel_code];
while (true) {
  if (event_queue.length === 0) {
    sleepUntilWokenUp();
  }
  if (event_queue.length > 0) {
    let callback = event_queue.shift();
    callback();
  }
}

where sleepUntilWokenUp() is a special function that suspends the current thread until another thread sends some signal to wake it up. Async operations (like file system or network access) are handled by such other threads. When they have a callback ready to execute, they will enqueue it and then send the appropriate wake-up signal.

You can imagine setImmediate(callback) as being implemented as event_queue.push(callback).

"Transferring control" from the event loop to a callback simply means calling the callback; "returning control" to the event loop simply means that the callback function returns.

Long-running "async" tasks always decompose into snippets that run on the main thread, schedule some work to be done (typically on another thread), then return. Once the requested task has been completed in the background, their corresponding callback is enqueued. Even "synchronous" calls with await are just syntactic sugar for splitting the function in two halves such that the first half runs to completion, and the second half is pushed onto the event_queue when the awaited task has completed.

The full situation in reality is somewhat more complicated (and described in detail in the Node documentation) with a few different queues for different kinds of things, but the above describes the general idea.

Post a Comment for "What Is The Exact Handling Of The Nodejs Event Loop?"