【问题标题】:Callback won't be called in recursive function不会在递归函数中调用回调
【发布时间】:2016-01-18 10:19:01
【问题描述】:

我不明白为什么在下面的函数中不会调用回调。奇怪的是,除了 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);

这是我的问题的解决方案,但我不确定我是否理解它的工作原理。感谢您的帮助。

【问题讨论】:

  • typeof callbackfunction 吗?
  • 你怎么知道它没有被调用?您没有发布回调函数本身的样子,也没有发布 get_page() 本身最初被调用的方式。
  • 是不是因为您的测试用例从未通过else 块?
  • @Pointy :我已经更新了代码以包含调用。
  • @Chris'o:我确定它会通过 else 块,因为控制台会被输出。

标签: javascript asynchronous recursion callback


【解决方案1】:

您是否尝试过在 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 ?

    });
}); 

}

【讨论】:

  • 你也可以在你的代码中加入“debugger”关键字,一步一步检查你的方法为什么没有执行。
  • 谢谢,但它必须在 else 语句中,因为那是该过程完成的时候。
  • 哪个“过程”/方法?
  • 对不起,我的意思是我只能在函数的目的完成时调用回调。在这种情况下,该函数会抓取网站。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-21
  • 2015-09-12
  • 1970-01-01
  • 2019-08-23
  • 2011-01-22
相关资源
最近更新 更多