回调 - 第二次回调后出错

时间:2015-12-28 21:53:10

标签: javascript node.js callback asynccallback

我正在学习回调,我写了这段代码:

var http = require('http');
var str = "";
var count = 2;
function jugglingAsync(callback){
    http.get(process.argv[count], function(response){
        response.on("data", function(data){
            str+=data.toString();
        })
        response.on("end", function(){
            console.log(str);
            str = "";
            count++;
            if(count<5) callback();
        })
    })
}
jugglingAsync(jugglingAsync);

它应该收集作为命令行参数给出的3个URL地址。问题是 - 当第一次回调工作正常并打印出好的结果时,第二次给我一个错误:

            if(count<5) callback();
                        ^

TypeError: callback is not a function
    at IncomingMessage.<anonymous> (/home/dzikichrzan/Gdrive/Programowanie/JavaScript/learnyounode/jugglingAsync.js:13:16)
    at emitNone (events.js:73:20)
    at IncomingMessage.emit (events.js:167:7)
    at endReadableNT (_stream_readable.js:906:12)
    at nextTickCallbackWith2Args (node.js:455:9)
    at process._tickCallback (node.js:369:17)

为什么这个功能只运行一次?

1 个答案:

答案 0 :(得分:1)

你正在调用

中的jugglingAsync

if(count&lt; 5)callback();

没有参数,期望参数作为回调函数