javascriptnode.jscallbackasync.jssetimmediate

nodejs: When should I use `setImmediate(cb)` vs `cb()`?


When reading on The Callback Hell , I came across two different ways of calling a callback function in the exact same example linked above (last example in the linked section):

cb();

and then

setImmediate(cb);

for seemingly exactly the same thing. When do I use which of the two versions?


Solution

  • With setImmediate you are posticipating the execution of the callback to the end of the event loop. What does that mean? Nodejs will handle the other functions calls before your cb.