带有包含请求的循环的回调数组

callback array with a loop containing request

本文关键字:循环 数组 回调 请求 包含      更新时间:2023-09-26

我试图返回食谱数组,但它似乎是空的。我猜那是因为回调在循环执行之前被执行。我怎么能解决这个在这种情况下,我循环与cheerio?

function scrapeNow(url, callback) {
  request(url, function(error, response, html){
    // First we'll check to make sure no errors occurred when making the request
    if(!error){
      var recipes = [];
      var $ = cheerio.load(html);
      $('div.article-block a.picture').each(function(i, elem) {
        console.log(i);
        var deepUrl = $(this).attr('href');
        if(!$(this).attr('href').indexOf("tema") > -1) {
          request(deepUrl, function(error, response, html){
            // First we'll check to make sure no errors occurred when making the request
            if(!error){
              var $ = cheerio.load(html);
              var image = $('div.article div.article-main-pic img').attr('src');
              var title = $('div.recipe h2.fn').text();
              var object = {url: deepUrl, title : title, image : image};
              recipes.push(object);
            }
          });
        }
      });
      callback(recipes);
    }
  });

}

我猜这是因为回调在循环执行之前被执行。

不,这是因为在你的循环中有另一个请求

request(deepUrl, function(error, response, html){

和recipes在此请求的完整回调(匿名函数)中填充。

callback(recipes)放到这个完整的回调中