【问题标题】:How to write node.js Async inside for loop?如何在 for 循环中编写 node.js Async?
【发布时间】:2016-02-12 06:24:21
【问题描述】:

我开始构建 nodejs 应用程序以从具有分页的站点中抓取数据。我编写 for 循环来获取所有页面并将所有 url 推送到存储在数组中。在那个 for 循环中,我编写 async.eachSeries 来逐个运行所有 url,在它完成运行后我想打印出成功消息。但我不知道如何将它们组合在一起以使其正常工作。这是我的代码

for(var pageNo = 1; pageNo <=200; pageNo++){
  siterequest('https://www...../en/jobs/?by=&in=&page='+pageNo, function(err, res, body){
    if(!err && res.statusCode ==200){
        var $ = cheerio.load(body);
        var links = [];
        $('.headline3.job-name-title > strong > a').each(function(i, elem){
            links.push('https://www......com.kh/'+$(elem).attr('href'));
        });
        async.eachSeries(links, function(uri, next){
            console.log('i will go this '+uri);
            next();
        }, function(callback){
            console.log('I did it');
        });
      };
  });
};

上面的代码对我不起作用。请帮我! 提前致谢

【问题讨论】:

  • 去掉for循环末尾的分号

标签: javascript node.js


【解决方案1】:

当您使用 async.js 时,您可以尝试使用 async.times 而不是 for loop

async.times(200, function (paneNo, nextPage) {
  siterequest('https://www...../en/jobs/?by=&in=&page=' + (pageNo + 1), 
    function (err, res, body) {
      if (!err && res.statusCode ==200) {
        var $ = cheerio.load(body);
        var links = [];

        $('.headline3.job-name-title > strong > a').each(function (i, elem) {
          links.push('https://www......com.kh/'+$(elem).attr('href'));
        });

        async.eachSeries(links, function (uri, next) {
          console.log('i will go this '+ uri);
          next();
        }, function(callback) {
          nextPage();
        });
      } else {
        nextPage(err);
      }
  });
}, function(err) {
  console.log('Done!');
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-08
    • 2022-01-27
    • 1970-01-01
    • 2019-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-07
    相关资源
    最近更新 更多