2015-10-19 113 views
0

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

这是我的问题的解决方案,但我不知道我明白它为什么起作用。谢谢您的帮助。

+0

是'typeof运算callback'了'function'? –

+0

你究竟知道它没有被调用?您没有发布回调函数本身的样子,也没有发布最初调用'get_page()'本身的方式。 – Pointy

+0

是否因为你的测试用例从未经过'else'块? –

回答

0

你试过在你后面执行回调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 ? 

    }); 
}); 

}

+0

您也可以在代码中添加“调试器”关键字,并逐步检查您的方法未执行的原因。 – wawawoom

+0

谢谢,但它必须在else语句中,因为那是进程完成时的情况。 – AppTest

+0

哪个“过程”/方法? – wawawoom