Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parallel Request at different paths in NodeJS: long running path 1 is blocking other paths

Tags:

node.js

I am trying out simple NodeJS app so that I could to understand the async nature.

But my problem is as soon as I hit "/home" from browser it waits for response and simultaneously when "/" is hit, it waits for the "/home" 's response first and then responds to "/" request.

My concern is that if one of the request needs heavy processing, in parallel we can't request another one? Is this correct?

    app.get("/", function(request, response) {
        console.log("/ invoked");
        response.writeHead(200, {'Content-Type' : 'text/plain'});
        response.write('Logged in! Welcome!');
        response.end();
    });

    app.get("/home", function(request, response) {
        console.log("/home invoked");
        var obj = {
            "fname" : "Dead",
            "lname" : "Pool"
        }
        for (var i = 0; i < 999999999; i++) {
            for (var i = 0; i < 2; i++) {
                // BS
            };  
        };
        response.writeHead(200, {'Content-Type' : 'application/json'});
        response.write(JSON.stringify(obj));
        response.end();
    });
like image 895
rohitpal Avatar asked Nov 01 '22 23:11

rohitpal


1 Answers

Good question, Now, although Node.js has it's asynchronous nature, this piece of code:

for (var i = 0; i < 999999999; i++) {
    for (var i = 0; i < 2; i++) {
        // BS
    };  
};

Is not asynchronous actually blocking the node main thread. And therefore, all other requests has to wait until this big for loop will end.

In order to do some heavy calculations in parallel I recommend using setTimeout or setInterval to achieve your goal:

var i=0;
var interval = setInterval(function() {
   if(i++>=999999999){
       clearInterval(interval);
   }
   //do stuff here
},5);

For more information I recommend searching for "Node.js event loop"

like image 71
Stasel Avatar answered Nov 12 '22 17:11

Stasel