learnyounode exercise 9 - 输出显示未定义,问题理解异步或逻辑

时间:2017-03-20 09:08:22

标签: javascript arrays asynchronous

我一直在努力完成JUGGLING ASYNC上的learnyounode任务。据我所知,我正在做几乎正确的事情,看起来这个问题就在我自己试图避开bl或其他模块的情况下。我在没有其他模块的情况下完成了上一个任务,并希望继续这种趋势。

const http = require('http');
const url = process.argv[2];

let content = [];
let count = 0;

const arguments = process.argv;
let urlArray = arguments.filter(function pullUrls(element, index, array) {
    return index >= 2;
});

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

function httpGet(index) {
    http.get(urlArray[index], function(response){
        response.on('data', function(data){

            newData = data.toString();
            content[index] = content[index] + newData;
        })
        response.on('end', function(){
            count++;
            if (count === 3){
                printResults();
            }
        })
    })
}

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

常见输出非常接近预期,但在开头包含undefined字符串,我无法弄清楚原因。

undefinedLets get some ute when we're going parma. Grab us a slab how it'll be bull bar. He's got a massive bushie where stands out like a pot. 
undefinedShe'll be right mongrel heaps as cross as a hit the turps. Stands out like a booze also you little ripper flick. As stands out like ironman when lets throw a bikkie. 
undefinedHe hasn't got a bounce with gutful of struth. Stands out like a aerial pingpong piece of piss built like a battler. 

正如您所看到的,它发现阵列未定义&#39;首先,这是真的,但随后附加到它上面。

我最好的猜测是,在content[index] = content[index] + newData;被发现之前,let content = []行以某种方式保持content[i]的未定义性质。现在我已经把它写出来并仔细思考了,这可能是一个简单的JS问题,我只是忽视或者不知道 - 我不知道。

任何帮助都会很好。

1 个答案:

答案 0 :(得分:1)

您的正确输出content[index]最初是未定义的,您可以在连接newData之前执行未定义的检查。这是包含更改的完整代码。

const http = require('http');
const url = process.argv[2];

let content = [];
let count = 0;

const arguments = process.argv;
let urlArray = arguments.filter(function pullUrls(element, index, array) {
    return index >= 2;
});

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

function httpGet(index) {
    http.get(urlArray[index], function(response){
        response.on('data', function(data){

            let newData = data.toString();
            //check if undefined
            if(typeof content[index] !== 'undefined'){
              content[index] = content[index] + newData;
            }else{
              //add newData if undefined
              content[index] = newData;
            }

        })
        response.on('end', function(){
            count++;
            if (count === 3){
                printResults();
            }
        })
    })
}

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