在递归函数中不能调用回调函数

Callback won't be called in recursive function

本文关键字:回调 函数 调用 不能 递归函数      更新时间:2023-09-26

我不明白为什么在下面的函数中不会调用回调。奇怪的是,除了else块中的回调之外的所有东西都会被调用。将回调放在if语句中的任何地方也可以。

我不明白为什么它会跳过回调。

var get_page = function(options, callback){
request_wrapper(c_url(options), function(xml){
    parseString(xml, function (err, result) {
        if(result["feed"]["entry"] != undefined){
            async.eachSeries(result["feed"]["entry"], function(entry, iter) {
                total_entries++;
                iter();
            },function(){
                options.start = total_entries;
                get_page(options, function(){
                });
            });
            // callback({}); works anywhere in the if statement.
        }else{ 
            callback({}); // Doesn't work here.
            // But this shows.
            console.log("TOTAL ENTRIES HERE: "+total_entries);   
            //So why is callback in the same block not being called?
        }
    });
}); 
}

这是我调用的函数,如果有帮助的话。正如我所说,它确实输出,只是不在else块中。

exports.scrape = function(options, callback){
    get_page(options, function(ob){
        console.log(ob);
    });
}

更新:我只是偶然发现了答案。递归调用不应该是这样的:

get_page(options, function(){
});

应该在函数形参中包含回调函数,如下所示:

get_page(options, callback);

这是我的问题的解决方案,但我不确定我理解为什么它工作。谢谢你的帮助。

您是否尝试将回调执行放在if/else之后?

var get_page = function(options, callback){
request_wrapper(c_url(options), function(xml){
    parseString(xml, function (err, result) {
        if(result["feed"]["entry"] != undefined){
            async.eachSeries(result["feed"]["entry"], function(entry, iter) {
                total_entries++;
                iter();
            },function(){
                options.start = total_entries;
                get_page(options, function(){
                });
            });
        }else{ 
            // But this shows.
            console.log("TOTAL ENTRIES HERE: "+total_entries);   
        }
        callback({}); // Does this work ?
    });
}); 

}