learnyounode JUGGLING ASYNC订单不稳定

时间:2017-02-21 12:22:14

标签: javascript node.js

我正在尝试learnyounode(https://github.com/workshopper/learnyounode
练习9 ## JUGGLING ASYNC(尝试3获取请求并以相同的顺序显示响应)

我在下面写了代码,但结果顺序不稳定。什么是错的?

var http = require('http');
var bl = require('bl');

var urls = [];

for (var i = 2; i < process.argv.length; i++ ) {
  urls.push(process.argv[i]);
};

var results = [];

for (var i = 0; i < urls.length; i++) {
  http.get(urls[i], function(response) {
    response.pipe(bl(function(err, data) {
      if (err) {
        console.error(err)
      };

// if this code results[i] = data.toString() // console.log shows “”    
      results.splice(i, 0 , data.toString());

      if ( results.length === urls.length) {
        for (var i = 0; i < results.length ; i++) {
          console.log(results[i]);
        }
      };
    }));
  });
}

官方答复如下。

var http = require('http')
var bl = require('bl')
var results = []
var count = 0

function printResults () {
  for (var i = 0; i < 3; i++) {
    console.log(results[i])
  }
}

function httpGet (index) {
  http.get(process.argv[2 + index], function (response) {
    response.pipe(bl(function (err, data) {
      if (err) {
        return console.error(err)
      }

      results[index] = data.toString()
      count++

      if (count === 3) {
        printResults()
      }
    }))
  })
}

for (var i = 0; i < 3; i++) {
  httpGet(i)
}

0 个答案:

没有答案