This document discusses the event loop in Node.js, which allows JavaScript to perform non-blocking I/O operations and asynchronous code. It explains that the event loop handles pending callbacks, timers, and incoming connections in different phases. Common asynchronous functions like setTimeout(), setImmediate(), and process.nextTick() are explained in terms of how they interact with the event loop. Finally, some common misconceptions about the event loop and asynchronous operations in Node.js are addressed.
SetImmediate() vs SetTimeout() setImmediate()is designed to execute a script once the current poll phase completes. SetTimeout() schedules a script to be run after a minimum threshold has elapsed
When to useProcess.nextTick() 1. To allow users to handle errors. 2. Run a request before starting the next iteration of event loop, or the other event loop continues. 3. Clean unwanted resources. 4. Allow callback to run after call stack and before next iteration of event loop.
Misconception 1: Everythingthat’s asynchronous like talking with database, working with filesystems is handled by a thread pool Reality: Libuv by default creates a thread poll with multiple thread to offload asynchronous work. Today’s operating system already provide asynchronous interfaces for many I/O tasks. Whenever possible libuv will use those interfaces avoiding usage of thread pool. But if there is no other option the thread pool will be used for asynchronous I/O/
27.
Misconception 2: EventEmitterand Event loop are related. NodeJs event loop is the heart of Nodejs which provide non-blocking and asynchronous behaviour of an application, while eventemitter is extensively used when writing the NodeJs application.