【发布时间】: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 callback是function吗? -
你怎么知道它没有被调用?您没有发布回调函数本身的样子,也没有发布
get_page()本身最初被调用的方式。 -
是不是因为您的测试用例从未通过
else块? -
@Pointy :我已经更新了代码以包含调用。
-
@Chris'o:我确定它会通过 else 块,因为控制台会被输出。
标签: javascript asynchronous recursion callback