I know that articles and tutorials were not once created on this topic. But still. Why this code can process requests only sequentially despite the fact that it is built using setImmediate:

var http = require('http'), replicate, fileServer; replicate = function (symbol, count) { var str = "", i; for (i = 0; i <= count; i += 1) { str += symbol; } return str; }; fileServer = function (response) { var Klength = 1024, i = 0; response.writeHead(200, { 'Content-Type': 'text/plain', 'Content-Length': 1024 * Klength }); setImmediate(function f() { for (; i < Klength; i += 1) { response.write(replicate('A', 5)); setImmediate(f); return; } response.end(); }); }; http.createServer(function (request, response) { if (request.url === '/favicon.ico') { response.writeHead(404); response.end(); return; } fileServer(response); }).listen(8000); 

The same problem with this implementation:

 fileServer = function (response) { var Klength = 1024 * 1024, i = 0, emiter; response.writeHead(200, { 'Content-Type': 'text/plain', 'Content-Length': Klength }); emiter = new events.EventEmitter(); emiter.addListener('continue', function () { if (i <= Klength) { response.write('A'); i += 1; setImmediate(function () { emiter.emit('continue'); }); return; } response.end(); }); emiter.emit('continue'); }; 
  • So it is ... - asynchronously does not mean parallel. - zb '
  • ok i got it Then the question is how can I deal with such situations. After all, they still can not be avoided? - andreycrane
  • It turns out that splitting a handler into a series of asynchronous calls does not give you the opportunity to run several instances of it? - andreycrane
  • see, starting the process asynchronously, you just allow other processes that have received the event to execute. Do you have any problem at all? slow emit blocks other clients or what? - zb '
  • The problem is that no other request goes to processing this handler until it handles the previous one. Simply speaking, after accessing it from one browser tab, you will not receive a response to another until you complete the first request. What is interesting is that other handlers respond without delay. Exactly this moment is not clear to me. - andreycrane

1 answer 1

Long calculations should be carried out in a separate process. if you execute js code without accessing I / O, it will be blocked. those. the function must complete its execution, and you just have a call from each other going on. setImmediate simply modifies the call queue, but on i / o it is not interrupted and all should be executed.