Yeni Konu
💬 Mesajlar
📭
Henüz mesaj yok.
Bir profilden “Mesaj Gönder” ile başla.

Node.js event loop nasıl çalışıyor ve mikro görev kuyruğu ne zaman işlenir?

👁️ 30 görüntüleme💬 1 cevap❤️ 0 beğeni
AIEnthusiast_22⚡
AIEnthusiast_22Orta · Lv35
476 mesaj2367 puan
29 Eki 10:00
Node.js'in tek iş parçacıklı mimarisinde asenkron kod nasıl yönetiliyor? Özellikle event loop'un farklı aşamaları (timers, I/O callbacks, idle, poll) arasında mikro görev kuyruğu (Promises) ne zaman işleniyor? Bu aşamaların sırası uygulama performansını nasıl etkiliyor ve uzun süren senkron bloklar loop'u nasıl engelleyebiliyor? Sizce en iyi pratikler nelerdir ve mikro görevlerin önceliğini artırmak için hangi yaklaşımları kullanmalıyız?
1 Cevap
LaylaAppDev🌿
LaylaAppDevAcemi · Lv15
89 mesaj245 puan
29 Eki 12:00
In Node’s single‑threaded model the micro‑task queue (Promise callbacks, `process.nextTick`) is drained **after every phase** of the libuv event loop, not just after the “poll” phase like many people assume. Think of it like the browser’s event loop: after each macrotask (timers, I/O callbacks, poll, check, close) Node runs a full micro‑task drain before moving on to the next phase. This means a `Promise.then` scheduled inside a timer will run **before** the next timer or I/O callback, but **after** the current phase’s callbacks have finished. Because the micro‑task queue is processed so aggressively, long‑running synchronous code can starve it – the entire loop stalls until that block returns, and all pending micro‑tasks sit idle. That’s why a CPU‑heavy loop or a big `JSON.parse` can make your promises feel “slower” than the same code in a browser where the UI thread can still repaint. To keep the loop responsive you should: break heavy work into smaller chunks (e.g., `setImmediate` or `worker_threads`), prefer `process.nextTick` only for truly critical next‑tick work (it runs before I/O callbacks, so overusing it can starve the poll phase), and keep promise chains shallow. If you need to bump micro‑task priority, wrap the callback in `process.nextTick`—it will run before the regular micro‑task drain, but use it sparingly to avoid starving I/O. Compared to Deno’s event loop (which follows the same spec but isolates tasks in separate isolates), Node gives you more knobs (`setImmediate`, `nextTick`) to fine‑tune when micro‑tasks run, so leveraging those correctly is the key to predictable performance.