martinho
martinho

Reputation: 3379

In Nodejs, why synchronous code is executed before asynchronous?

I have this code:

console.log('1');
process.nextTick(() => console.log('inside nextTick'));
setImmediate(()=> console.log('inside setImmediate'));
console.log("2");
for(var i=0;i<1 ; i++) {
    console.log("inside for loop");
}

And output is:

1
2
inside for loop
inside nextTick
inside setImmediate

Please explain why it is happening. Even if I have written console.log("2"); and the for loop after process.nextTick and setImmediate, why are they executing before them?

Upvotes: 1

Views: 169

Answers (2)

SNG
SNG

Reputation: 357

Asynchronous is a behaviour, if we have two lines of code Line-1 followed by Line-2. Line-1 is a time-consuming instruction. So Line-1 starts executing its instruction in the background (like a daemon process), allowing Line-2 to start executing without having to wait for Line-1 to finish. We need this behaviour when things are slow. Synchronous executions of code may seem straightforward but can be slow. Tasks like image processing can be slow, file operations can be really slow, making network request and waiting for response is definitely slow, making huge calculations like over a 100 million for-loop iteration is somewhat slow. So such slow things in Call stack results in “Blocking”. When call stack is blocked, the browser prevents user’s interrupts and other code statements from executing until the blocking statement is executed and the call stack is freed. Hence Asynchronous callbacks are used to handle such situations.

ex:
console.log("Hello");
setTimeout(function(){ console.log("Susi");},2000);
console.log("Iam");

o/p: Hello, Iam susi.

In your example first it will print the console statements because process.next will execute in the next iteration of event loop and then setimmediate. due to that your getting the output as below.

1
2
inside for loop
inside nextTick
inside setImmediate

Upvotes: 0

Barmar
Barmar

Reputation: 780724

That's how asynchronous code works in JavaScript. When you schedule asynchronous code, it's added to the event queue. This is processed by the main event loop, which only gets control when synchronous code returns. So all the synchronous code runs, which logs all those message, then it returns to the main event loop, which invokes all the asynchronous tasks.

Upvotes: 2

Related Questions