Reputation: 2562
If one request will be take a long time for execution, another tabs will wait until first request will completed. Why? Please explain me. And how to solve it? Here my code:
var http = require("http");
var url = require("url");
http.createServer(function(request, response) {
if (url.parse(request.url).pathname == '/long')
{
function longlong()
{
var counter = 0;
var startTime = new Date().getTime();
while (new Date().getTime() < startTime + 10000)
{
counter++;
}
return counter;
}
response.writeHead(200, {"Content-Type": "text/plain"});
response.write(longlong() + '');
response.end();
}
else
{
response.writeHead(200, {"Content-Type": "text/plain"});
response.write(0 + '');
response.end();
}
}).listen(8888);
Upvotes: 2
Views: 3063
Reputation: 39296
Good read:
http://blog.mixu.net/2011/02/01/understanding-the-node-js-event-loop/
A key line from that write up is:
…however, everything runs in parallel except your code
That means expensive I/O should be async but your code can block. but, it's typically expensive I/O that we're worried about blocking on the server.
See this other question for more details with an example: Node.js blocking the event loop?
Upvotes: 3
Reputation: 56477
Because NodeJS is single threaded ( just like browser JavaScript ). It can only process one code at a time. We get the illusion of concurrency, because NodeJS has very fancy queue of code blocks which are fired in an asynchronous way. However once the block is processed no other block can be processed at the same time.
With NodeJS you have to make sure that every request ends (either successfuly or not), otherwise it may crash beyond any help (entire server, not only the request).
Also using process.nextTick
instead of classical loop may help your requests work faster ( i.e. be more scalable ).
Upvotes: 1