NodeJS eventloop执行顺序

当连续发送几个请求时,看起来像

  • 发送所有请求时执行callback。
  • 请求似乎被添加到队列中,但在循环完成之前并没有真正执行。

var http = require('http'); var i=0; var postData = []; while (i++ < 12) { var largeObject = [ 'this' + i, 'that' + i, 'then' + i ]; postData.push(largeObject); if (postData.length >= 2) { console.log('request'); var options = { hostname: 'httpbin.org', port: 80, path: '/post', method: 'POST', headers: { 'Content-Type': 'application/json', } }; var req = http.request(options, function(res) { console.log(res.statusCode); res.on('data', function(chunk) { console.log(chunk.toString()); }); res.on('end', function() { console.log('finished reading response'); }); }); req.end(JSON.stringify(postData), function() { console.log('request stream finished'); }); postData = []; } } 

这里的输出看起来像

 request request request request request request request stream finished request stream finished request stream finished request stream finished request stream finished request stream finished 200 { "args": {}, "data": "[[\"this7\",\"that7\",\"then7\"],[\"this8\",\"that8\",\"then8\"]]", "files": {}, "form": {}, "headers": { "Content-Length": "53", "Content-Type": "application/json", "Host": "httpbin.org" }, "json": [ [ "this7", "that7", "then7" ], [ "this8", "that8", "then8" ] ], "origin": "xxxxx", "url": "http://httpbin.org/post" } finished reading response 200 { "args": {}, "data": "[[\"this1\",\"that1\",\"then1\"],[\"this2\",\"that2\",\"then2\"]]", "files": {}, "form": {}, "headers": { "Content-Length": "53", "Content-Type": "application/json", "Host": "httpbin.org" }, "json": [ [ "this1", "that1", "then1" ], [ "this2", "that2", "then2" ] ], "origin": "xxxx", "url": "http://httpbin.org/post" } ... 

有什么办法在下一个执行之前完成一个请求?

我真的不关心这个顺序,而是关于记忆 – 我想摆脱我发布的大型对象

例如

 request1 response1 request2 response2 request3 response3 request4 request5 response5 response4 

将是绝对好的。 任何build议?

当然,只要使用一些控制stream模块,如asynchronous或蓝鸟。

由于您不关心订单,我build议您使用async#parallel或bluebird#map 。 bluebird#map有一个并发的参数,当你需要更多的控制循环及其数量( async#parallelLimit )的时候,这可能是很好的。

如果这看起来不直接,请评论,我会添加一个例子。