在递归函数中不能调用回调函数
Callback won't be called in recursive function
我不明白为什么在下面的函数中不会调用回调。奇怪的是,除了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 ?
});
});
}
相关文章:
- JavaScript回调函数
- 如何在回调函数中执行流
- 回调函数中传递参数的困难(Google Map API Markers)
- 如何正确地将参数传递给RequireJS回调函数
- 回调函数在python代码中离线
- 从AJAX回调函数中分离数据
- 赋值后的回调函数
- 如何在javascript回调函数中返回多个变量
- 函数表达式,返回回调函数
- 等待回调函数执行
- JavaScript回调函数和Google Feed API
- 如何从ajax成功回调函数中读取javascript变量
- 正在保存JavaScript内部回调函数中的值
- 有没有什么方法可以停止Jquery中的animate(也可以停止完整的回调函数)
- 如何在javascript中添加带有回调函数的按钮点击事件作为window.conf
- 在Golang回调函数中启用CORS
- 在初始函数完成之前调用回调函数
- jQuery Mobile:如何在$.Mobile.changePage之前运行回调函数
- 即使使用回调函数也无法返回值
- 为什么prototypjs观察到回调函数有绑定