The Call Stack in Node.JS

Asynchronous code will never run before Synchronous code.

Check this out:

// Asynchronous Code
setTimeout(function(){
console.log("exiting now");
process.exit();
}, 0)
// Synchronous (Blocking) Code
var x = 100000;
while(x){
console.log(x);
x--;
}

Guess what runs first? The while loop. While the blocking code is running, the async code will not run. It won’t “jump in” mid loop. It can only run after all the synchronous code is done.

For instance, it won’t ‘jump in’ after the while loop either.

setTimeout(function(){
console.log(“exiting now”);
process.exit();
}, 0)
var x = 100000;
while(x){
console.log(x);
x — ;
}
for (var x = 0; x < 1000; x++){
console.log(“exiting now 1.5”);
}

The async code will run after the for loop too.