learnyounode杂耍异步解决方案不工作

learnyounode Juggling Async Solution not working

本文关键字:工作 解决方案 异步 learnyounode      更新时间:2023-09-26

我已经研究了这个主题的其他线程,但仍然不明白为什么我的线程不起作用。有什么想法吗?

var files = process.argv.slice(2);
var count = 0;
var results = [];
var http = require('http');
function printOut() {
    for (var t = 0; t < results.length; t++) {
        console.log(results[t]);
    }
}
function run(id){
    http.get(files[id], function(response) {
        var output = '';
        count++;
        response.setEncoding('utf8');
        response.on("data", function(data) {
            output += data;
        });
        response.on("end", function() {
            count--;
            //console.log(count);
            results[id] = output;
            if (count === 0) {
                printOut();
            }
        });
        }).on('error', function(e){
                console.log("error:" + e.message);
            });
}
for(var j = 0; j < files.length; j++){
    //console.log('Running ' + (j+1) + 'st get');
    run(j);
}

我已经看了好几个小时了,不明白为什么它不起作用。

您是如何运行的?

我更改了你程序中的一行:http.get('http://www.google.com/', function(response) {

并执行:node index.js hellohello只是一个占位符,因为for循环需要一个参数)。它对我来说很好。所以也许你需要详细说明一下?