ng.newbie
ng.newbie

Reputation: 3227

Node.Js Are all sync calls guaranteed to be executed before async calls?

I am new to NodeJS and I am trying to get my head around how the event loop works in various scenarios.

Take the following code snippet :

console.log("Hello");

setImmediate(() => {
    console.log("Immediate");
    });

console.log("World");

It gives the following output:

Hello
World
Immediate

It only makes sense if you are willing to believe that all async calls happen after all sync calls.

Is that true ? Are all node sync calls suppose to execute before the async calls.

When does the event loop event start ? After parsing the whole file or when the node runtime starts up ? Or when it encounters the first async call ?

I can rationalize the above output only if I accept one of the presumptions, either all async calls happen after sync calls, ie. event loop starts after all sync calls are completed, or setImmediate() here takes more time to complete than console.log()

Which one is correct ?

Upvotes: 1

Views: 74

Answers (1)

Rob M.
Rob M.

Reputation: 36521

The call stack is populated from synchronous calls (console.log) and the event queue is populated with asynchronous calls (setImmediate). The call stack must be emptied completely before the event loop processes the event queue. Here is effectively what your program looks like on the call stack and event queue:

State 1:

stack                        queue
[console.log('Hello')]       [setImmediate(() => ...)]
[console.log('World')]

State 2:

stack                        queue 
[console.log('World')]       [setImmediate(() => ...)]

State 3:

stack                        queue 
                             [setImmediate(() => ...)]

State 4 (event loop dequeues and pushes to call stack):

stack                        queue 
[console.log('Immediate')]

State 5 (done):

stack                        queue 

You can see a more accurate animation of it here: http://latentflip.com/loupe/?code=Y29uc29sZS5sb2coJ0hlbGxvJykKCnNldFRpbWVvdXQoZnVuY3Rpb24oKSB7CiAgICBjb25zb2xlLmxvZygnSW1tZWRpYXRlJykKfSwgMCkKCmNvbnNvbGUubG9nKCdXb3JsZCcp!!!PGJ1dHRvbj5DbGljayBtZSE8L2J1dHRvbj4%3D

Javascript is single-threaded, meaning that it only has one call stack. Browsers (and Node) provide asynchronous APIs to take potentially blocking items off of the call stack and move them to the event queue so that the engine can continue processing the call stack (and not freezing the browser/server) and effectively "background" long-running or blocking operations.

Upvotes: 2

Related Questions