简体   繁体   中英

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM