What is Event Loop in Node.jsWhat is Event Loop in Node.js??
What is Event Loop in Node.jsWhat is Event Loop in Node.js??
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:
setTimeout()
and setInterval()
.setImmediate()
callbacks.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
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào