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

  1. Callback Queue - Stores callbacks that are ready to be executed after I/O operations.
  2. Microtask Queue - Handles promises and other microtasks, executed before the next I/O cycle.
  3. Poll Phase - Checks for new I/O events and processes them.
  4. Timers Phase - Executes timeouts and intervals.
NodeJS_Event_Loop

📌 How the Event Loop Works

  1. Node.js starts by executing the synchronous code.
  2. When an asynchronous operation (e.g., setTimeout, fs.readFile) is called, it is handed to the browser or OS for processing.
  3. Once the operation completes, the callback is added to the callback queue.
  4. The event loop checks the queue and executes the callbacks in the order they were added.
Event_Loop_Workflow

🧪 Code Example

console.log('Start');  

setTimeout(() => {  
  console.log('Timeout');  
}, 0);  

Promise.resolve().then(() => {  
  console.log('Promise');  
});  

console.log('End');  

Output:

Start  
End  
Promise  
Timeout  

📚 Further Reading

Event_Loop_Code_Example