0

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?

SCBuergel
  • 1,613
  • 16
  • 26

1 Answers1

0

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.

pietrovismara
  • 6,102
  • 5
  • 33
  • 45
  • With "handle the other functions calls before your cb" you mean that in `setImmediate(cb); a(); b(); c();`, the functions `a`, `b` and `c` are being executed before `cb`? – SCBuergel Jan 19 '17 at 13:00
  • If `a`, `b` and `c` are asynchronous then yes. – pietrovismara Jan 19 '17 at 13:02
  • 1
    When `setImmediate(cb);` is called, it will be entered in the 'uv__loop'. When all the function calls in the 'uv__loop' got executed then the execution of the callback in setImmediate will be resumed. In uv__loop the priority is: 1. Normal Callback functions 2. SetImmediate functions 3. Timer functions – Lakshmi Swetha G Feb 14 '17 at 12:36
  • @LakshmiSwethaG Adding your comment to my answer. – pietrovismara Feb 14 '17 at 13:47