setTimeout()
is "non-blocking". That means it sets the timer, returns immediately from the setTimeout()
and then continues to execute the rest of the code.
So, in your case /route2
creates the two promises, sets two timers and then waits for Promise.all()
to finish. At the point it hits the await
, your async
route handler returns a promise and returns control back to the event loop.
So, as soon as the /route1
request arrives, it's ready to be processed. /route2
is not active until both timers are done.
Then, when the longer timer is ready to fire, the next time the JS interpreter goes back to the event loop to check for anything else to do, it will see that timer, process the timer callback and that timer callback will resolve the p1
promise and then cause the Promise.all()
to be resolved.
If i hit /route2 , i get reponse 15s later,but during that time /route1 gives response immediately. Shouldn't server wait for 15s and then give reponse to /route1.
As explained about setTimeout()
is non-blocking so while the /route2
handler is waiting for the two timers to fire, nodejs is free to process other events (like the incoming /route1
event).
What i understood is as /route2 is hit console P1 then as there is setTimeout() ,put it in external thread,then console P2 then as setTimeout() ,put it in external thread.Now wait for setTimeouts() to finish.
Timers are not run in external threads. They are a somewhat unique design in the nodejs event loop. Timers are stored in a sorted linked list in the order of when they are due. Each time the JS interpreter gets back to the event loop and gets to the timer section of the event loop, it just checks the front most timer in the linked list to see if its time has arrived. If so, it triggers that event. If not, it just goes and looks for other types of events.
Eventually, if the event loop has nothing to do and goes to sleep, it will sleep for an appropriate time to wake up in time for the next timer scheduled to run (if nothing else wakes it up before that).
(At this time the event loop must be busy as it waiting for p1 and p2 fullfillment,so it should accept no new client request). But it does.Why?
This is your main wrong assumption. At this time, the event loop is entirely free to process other events. The two timers are set and the event loop will run their callbacks when their time is due, but until then the event loop will process any other incoming events like the /route1
request.
/route2
request sets it two timers and then returns control back to the system so nodejs is ready to process/route1
when it arrives.app.get()
defines a route rather than causing a route to be followed. And after a route is defined, any number of client requests can, over time, follow it.