Node.js 的事件循环(Event Loop)是其核心机制,使 JavaScript 能在非阻塞方式下处理异步操作。理解事件循环对于编写高效、可预测的 Node.js 应用至关重要。
🔄 What is the Event Loop?
The event loop is a single-threaded loop that processes asynchronous operations in the background, allowing Node.js to handle multiple requests efficiently. It continuously checks for new tasks and executes them without blocking the main thread.
🧠 Key Components of the Event Loop
- Callback Queue - Stores callbacks that are ready to be executed after I/O operations.
- Microtask Queue - Handles promises and other microtasks, executed before the next I/O cycle.
- Poll Phase - Checks for new I/O events and processes them.
- Timers Phase - Executes timeouts and intervals.
📌 How the Event Loop Works
- Node.js starts by executing the synchronous code.
- When an asynchronous operation (e.g.,
setTimeout
,fs.readFile
) is called, it is handed to the browser or OS for processing. - Once the operation completes, the callback is added to the callback queue.
- The event loop checks the queue and executes the callbacks in the order they were added.
🧪 Code Example
console.log('Start');
setTimeout(() => {
console.log('Timeout');
}, 0);
Promise.resolve().then(() => {
console.log('Promise');
});
console.log('End');
Output:
Start
End
Promise
Timeout