Can some some one please explain the realtime usecase of setImmediate() function in nodejs.I've gone through many blogs but every where they gave console.log example with setImmediate.
setImmediate()
is useful when you want to defer running some code or calling some callback until AFTER the current event has been fully processed and control returned back to the event loop.
There are a number of different reasons why you might want to do that:
You want other (already pending) events to have a chance to get processed before you run some code.
You want to call a callback, but you want to call it asynchronously so that the callers code that comes after gets to run before you call the callback. There are places in the nodejs library where it does this to guarantee that a callback is always called asynchronously, even if the result is known synchronously. This creates programming consistency for the caller so that the callback is not called synchronously sometimes and asynchronously sometimes which can lead to subtle bugs.
When you're trying to not block the event loop for too long. You may run a chunk of code, then call setImmediate()
and run the next chunk of code when the setImmediate()
callback gets called and so on. This allows the processing of other events that arrive in the event loop in between your chunks of processing.
Set this article for an easy-to-read summary of setImmediate()
, setTimeout()
and process.nextTick()
:
Here are some examples from the nodejs and Express source code:
Socket: Ensure that write is dispatched asynchronously
HTTP: Make sure parser is not deleted until stack has unwound
Express calls callback in layer routing only after stack has unwound
Express calls callback sendFile()
callback upon abort, only after stack has unwound