【问题标题】:Pass variable to nodejs function将变量传递给nodejs函数
【发布时间】:2015-02-09 13:26:58
【问题描述】:

我有一个简单的 nodejs 函数,应该如下工作:

  1. 向 url 列表发出 GET 请求。
  2. 收集对数组的所有响应。
  3. 逐行打印回复。

问题是我在开始时初始化 results 数组,在函数中间我将响应字符串推送到这个数组,但最后这个数组是空的。

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);

所以响应只是“[]”。

【问题讨论】:

标签: javascript arrays node.js get


【解决方案1】:

正如 cmets 中所指出的,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

希望对你有帮助。

【讨论】:

    【解决方案2】:

    这里 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
           });
    

    它对我有用。

    【讨论】:

      【解决方案3】:

      谢谢大家的回复,他们正在工作,但我找到了“bl”的答案。

      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()
                  }
              }))
          })
      }
      

      【讨论】:

        猜你喜欢
        • 2021-04-10
        • 2023-03-05
        • 1970-01-01
        • 1970-01-01
        • 2020-07-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多