process.nextTick() chạy trước cả Promise microtasks (không thuộc event loop phase) — recursive nextTick sẽ starve I/O; dùng setImmediate() trong hầu hết cases. process.nextTick() không thuộc bất kỳ phase nào của event loop — callbacks được đặt vào nextTick queue và chạy ngay sau synchronous code hiện tại kết thúc, trước khi event loop tiếp tục phase tiếp theo (kể cả trước Promise microtasks). setImmediate() thuộc check phase.
- Thứ tự ưu tiên: synchronous code → nextTick queue → Promise microtasks → event loop phases (timers → poll → check/setImmediate).
- Starvation danger: recursive
process.nextTick()sẽ block event loop mãi mãi — không bao giờ cho I/O callbacks chạy. - Node.js docs khuyên dùng
setImmediate()thay nextTick trong hầu hết trường hợp. - Khi nextTick phù hợp: emit event sau constructor return (để listener đăng ký kịp), propagate error asynchronously trong API mà phải consistent async.
- Khi setImmediate phù hợp: chia nhỏ heavy computation qua nhiều iterations mà vẫn cho I/O xen vào.
process.nextTick() fires before even Promise microtasks (not part of any event loop phase) — recursive nextTick starves I/O; prefer setImmediate() in most cases. process.nextTick() doesn't belong to any phase of the event loop — callbacks are placed in the nextTick queue and run immediately after the current synchronous code finishes, before the event loop continues to the next phase (even before Promise microtasks). setImmediate() belongs to the check phase.
- Priority order: synchronous code → nextTick queue → Promise microtasks → event loop phases (timers → poll → check/setImmediate).
- Starvation danger: recursive
process.nextTick()will block the event loop forever — I/O callbacks will never run. - Node.js docs recommend using
setImmediate()instead of nextTick in most cases. - When nextTick is appropriate: emitting events after a constructor returns (so listeners can register in time), propagating errors asynchronously in APIs that must be consistently async.
- When setImmediate is appropriate: breaking up heavy computation across multiple iterations while still allowing I/O to interleave.