node.js async juggling learnyounode tutorial

时间:2015-02-03 15:45:51

标签: node.js

我正在浏览learnyounode教程并且已经陷入了杂乱无章的问题。我在线搜索解决方案,我的代码看起来是一样的!我正在使用windows cmd。

它说的语法错误:意外的令牌)在i ++之后......我真的很困惑。不确定是怎么回事?

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


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

function gethttp (idx) {

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

            if (counter == 3)
                print()
                }))
})
}
      for (var i = 0; i < 3, i++)
      {
          gethttp(i)
      }

3 个答案:

答案 0 :(得分:1)

在最后一个'for'循环中,你有逗号而不是分号。

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

答案 1 :(得分:0)

下面的for循环有语法错误(逗号而不是分号):

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

应该是:

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

答案 2 :(得分:-1)

var http = require('http');

var links = [2, 3, 4];

var buffer = [];

(function render(index) {

    http.get(process.argv[links[index]], function (response){

        response.setEncoding('utf8');

        response.on('data', function(chunk){
            if(buffer[index] === undefined) {
                buffer[index] = '';
            }
            buffer[index] += chunk;
        });
        response.on('end', function () {
            var newIndex = index+1;
            if(links[newIndex] !== undefined) {
                render(newIndex);
            } else {
                return renderOutput();
            }
        });
        response.on('error', console.error);

    }).on('error', console.error);
})(0); //self-calling function

function renderOutput() {

buffer.forEach(function (elem) {

 console.log(elem);

    });

}