Trung BìnhNode.js iconNode.js

Event loop trong Node.js hoạt động như thế nào?

Node.js event loop xử lý async ops theo phases: timers→poll→check — giữa mỗi phase flush toàn bộ microtask queue (nextTick → Promises); thứ tự: process.nextTick(C), Promise.then(B), setTimeout(A, 0) → chạy C, B, A.

Event loop là vòng lặp liên tục xử lý callbacks theo 6 phases:

  1. Timers: thực thi callbacks của setTimeout/setInterval đã đến hạn;
  2. Pending callbacks: I/O errors từ vòng trước;
  3. Idle/prepare: internal use;
  4. Poll: fetch I/O events mới — nếu queue empty và không có timers pending, block tại đây chờ I/O;
  5. Check: setImmediate callbacks;
  6. Close callbacks: socket.on('close')

Giữa MỖI phase, Node.js xử lý toàn bộ microtask queue: Promise callbacks (then/catch) + queueMicrotask() + process.nextTick() (nextTick ưu tiên hơn Promise).

Starvation: nếu microtask queue không bao giờ empty (Promise resolve tạo Promise mới), event loop không bao giờ qua phase tiếp theo.

Ví dụ thực tế execution order: setTimeout(A, 0)Promise.resolve().then(B)process.nextTick(C) — thứ tự chạy: C, B, A.

Xem toàn bộ Node.js cùng filter theo level & chủ đề con.

Mở danh sách Node.js