1

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 the response to /route1.

I read https://medium.com/@cinish/nodejs-multiple-client-requests-694d6353218b but could not the idea.

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.

(At this time the event loop must be busy as it waiting for p1 and p2 fulfillment, so it should accept no new client request). But it does. Why?

app.get("/route1", (req, res) => {
    res.send("Route1");
});


app.get("/route2", async (req, res) => {

    const p1 = new Promise((resolve, reject) => {
        console.log("P1");
        setTimeout(() => {
            console.log(5);
            resolve();
        }, 15000);
    })
    const p2 = new Promise((resolve, reject) => {
        console.log("P2")
        setTimeout(() => {
            console.log(1);
            resolve();
        }, 1000);
    });

    const ans = await Promise.all([p1, p2]);
    res.send("Route2");
})
7
  • Client requests are (to all intent and purpose) independent of each other. Consider just how clogged up a Node server would be if threads, arising from potentially hundreds or thousands of client requests, blocked other threads. Commented Apr 2, 2020 at 1:14
  • Timers are managed by the event loop and only take up time in the main thread when executing the function.
    – Matt
    Commented Apr 2, 2020 at 1:46
  • and the tiny amount of time to check if there are any timers to execute on this go around the loop.
    – Matt
    Commented Apr 2, 2020 at 1:48
  • @Roamer-1888 - There are not two threads for these two requests. Nodejs still runs one request at a time here, but in this case, the /route2 request sets it two timers and then returns control back to the system so nodejs is ready to process /route1 when it arrives.
    – jfriend00
    Commented Apr 2, 2020 at 3:34
  • @jfriend00, but these aren't two requests, are they? Surely 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. Commented Apr 2, 2020 at 9:12

1 Answer 1

1

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.

2
  • I read about the call stack, node apis(worker threads) and event queue architecture. So timers are put into call stack, immediatley put into linked list (worker thread) and when the timeout happens pushed into event queue. I am confused, how promises are dealt.Are they done in the same way? Commented Apr 2, 2020 at 10:30
  • @RajatAggarwal - Promises have their own task queue that runs at a higher priority in the event loop (runs before other things waiting in the event loop). When a promise fires, it inserts a callback into the task queue and the next cycle through the event loop, nodejs grabs the calllback for the first promise in the task queue and runs that callback. But, promises still run through the event loop so they don't get to call their completion callbacks until the interpreter gets back to the event loop.
    – jfriend00
    Commented Apr 2, 2020 at 15:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.