NodeJS eventloop执行顺序

时间:2016-03-08 15:57:40

标签: node.js events

连续发送多个请求时,似乎是

  • 在发送所有请求时执行回调。
  • 请求似乎被添加到队列中,但实际上在循环完成之前没有执行。

示例

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"
}
...

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

我不太关心订单,更关心记忆 - 我想摆脱我发布的大件物品

e.g。

request1
response1
request2
response2
request3
response3
request4
request5
response5
response4

绝对没问题。 有什么建议吗?

1 个答案:

答案 0 :(得分:1)

当然,只需使用一些控制流模块,如async或bluebird。

由于您不关心订单,我建议您使用async#parallelbluebird#mapbluebird#map有一个并发参数,当你需要对循环及其数量进行更多控制时(async#parallelLimit也是如此),这可能很好。

如果这看起来不那么简单,请发表评论,我会添加一个例子。