Câu hỏi phỏng vấn Nodejs
Câu hỏi

What is Event Loop in Node.jsWhat is Event Loop in Node.js??

Câu trả lời

The Event Loop in Node.js is a fundamental mechanism that allows Node.js to perform non-blocking I/O operations, despite JavaScript being single-threaded. It is an endless loop that waits for tasks, executes them, and then sleeps until it receives more tasks. The event loop operates on the principle that it only executes tasks from the event queue when the call stack is empty, meaning there are no ongoing tasks. This design enables the use of callbacks and promises, which are essential for asynchronous programming.

Node.js offloads operations to the system kernel whenever possible, which can handle multiple operations in the background because most modern kernels are multi-threaded. When an operation completes, the kernel informs Node.js, and the appropriate callback is added to the poll queue to be executed eventually[1][2][3].

The event loop has several phases, each with its own queue of callbacks to execute. These phases include:

  • Timers: Executes callbacks scheduled by setTimeout() and setInterval().
  • I/O Callbacks: Executes callbacks associated with I/O events, excluding those to be executed immediately.
  • Idle, Prepare: Internal phase used for only specific internal operations.
  • Poll: Retrieves new I/O events; executes I/O related callbacks and determines how long to block and poll for I/O.
  • Check: Executes setImmediate() callbacks.
  • Close Callbacks: Executes callbacks for some closing connections like socket.on('close', ...).

The event loop also includes a microtask queue for operations that should be executed immediately after the current operation. This queue is processed after the execution of each callback and includes tasks scheduled by process.nextTick() and resolved promises[1][2].

In summary, the event loop enables Node.js...

middle

middle

Gợi ý câu hỏi phỏng vấn

middle

Provide your favourite reasons to use Node.js

middle

When should we use Node.js?

junior

What are the benefits of using Node.js?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào