Node.js uses an Event Loop
to handle Asynchronous operations. And by Asynchronous operations I mean all I/O operations like interaction with the system's disk or network, Callback functions and Timers(setTimeout, setInterval). If you put Synchronous operations like a long running for loop
inside a Timer or a Callback, it will block the event loop from executing the next Callback or I/O Operation.
In above case both /route1
and /route2
are Callbacks, so when you hit them, each callback is put into the Event Loop.
Below scenarios will give clear understanding on Asynchronous nature of Node.js:
- Hit
/route2
first and within 10 Seconds(Since setTimeout is for 10000 ms) hit /route1
In this case you will see the output Route 1 because setTimeout for 10 secs still isn't complete. So everything is asynchronous.
- Hit
/route2
first and after 10 Seconds(Since setTimeout is for 10000 ms) hit /route1
In this case you will have to wait till the for loop execution is complete
for(let i=0;i<1000000000000000;i++);
because a for loop
is still a Synchronous operation so /route1
will have to wait till /route2
ends
Refer below Node.js Guides for more details:
Blocking vs Non-Blocking
The Node.js Event Loop