将变量传递给nodejs函数

时间:2015-02-09 13:26:59

标签: javascript arrays node.js get

我有简单的nodejs函数,应该按照以下方式工作:

  1. 向网址列表发出GET请求。
  2. 收集对阵列的所有回复。
  3. 逐行打印回复。
  4. 问题是我在函数的开始和中间初始化结果数组我将响应字符串推送到此数组,但最后这个数组是空的。

    var http = require('http');
    var bl = require('bl');
    var argv = process.argv;
    var results = [];
    
        for (i = 2; i < argv.length; i++) {
        var url = argv[i].toString();
        http.get(url, function (response) {
            response.pipe(bl(function (err, data) {
                results.push(data.toString());  //if im just printing the data it shows the correct info.
            }))
        })
    
    }
    console.log(results);
    

    所以回应只是&#34; []&#34;。

3 个答案:

答案 0 :(得分:1)

正如评论中所指出的,http.get是异步工作的。因此,您必须使用其事件来填充数组,并等待所有这些事件完成以打印出结果。

你可以把它作为一个例子(不打算使用bl):

var http = require('http');
var argv = process.argv;
var results = [];

for (i = 2; i < argv.length; i++) {
    var url = argv[i].toString();
    http.get(url, function (response) {
        var res = '';
        response.setEncoding('utf8');

        response.on('data', function (data) {// Collect data.
            res += data;
        });

        response.on('end', function () {// Response's finished, print out array if we have collected all the requests.
            results.push(res);
            if (results.length === argv.length - 2) {
                console.log(results);
            }
        });
        response.on('error', console.log);
    });

}
//console.log(results);// This is not correct as it'll print out an empty array due to the asynchrous nature of http.get

希望它有所帮助。

答案 1 :(得分:1)

此处 http.get 正在异步工作。请尝试promise

        var http = require('http');
        var bl = require('bl');
        var argv = process.argv;
        var defer = require("promise").defer;
        var deferred = defer();
        var results = [];

            for (i = 2; i < argv.length; i++) {
            var url = argv[i].toString();
            http.get(url, function (response) {
                response.pipe(bl(function (err, data) {
                    results.push(data.toString());  //if im just printing the data it shows the correct info.

                }));
                deferred.resolve("succesful result");
            });
        }

       deferred.promise.then(function(result){
           console.log(results);
       },
       function(error){
          //... executed when the promise fails
       });

它对我有用。

答案 2 :(得分:0)

感谢大家的回复,这些都有效,但我找到了#34;&#34;。

var http = require('http');
var bl = require('bl');
var argv = process.argv;
var results = []

function printResults() {
    for (var i = 2; i < argv.length; i++)
        console.log(results[i])
}


for (i = 2; i < argv.length; i++) {
    var url = argv[i].toString();
    http.get(url, function (responce) {
        responce.pipe(bl(function (err, data) {
            results[i] = data.toString()
            if (count == 3) {
                printResults()
            }
        }))
    })
}