【问题标题】:Report completion of recursive function in node.js在 node.js 中报告递归函数的完成
【发布时间】:2018-04-19 03:23:51
【问题描述】:

我正在用 node.js 和 Electron 构建一个网络爬虫。

本质上,程序接收一个起始 URL,然后爬到一定深度,报告它在哪里找到了某些关键字。

到目前为止,这是有效的,但我无法弄清楚如何真正判断它何时完成。给定 3-4 的深度,这个程序似乎永远运行。对于较低的深度,真正判断它是否仍在爬行的唯一方法是查看它正在使用的 CPU/内存量。

这是执行爬取的函数:

function crawl(startingSite, depth) {
if (depth < maxDepth) {
    getLinks(startingSite, function (sites) { //pulls all the links from a specific page and returns them as an array of strings
        for (var i = 0; i < sites.length; i++) { //for each string we got from the page
            findTarget(sites[i], depth); //find any of the keywords we want on the page, print out if so
            crawl(sites[i], depth + 1); //crawl all the pages on that page, and increase the depth
        }
    });
}
}

我的问题是,我不知道如何让这个函数在完成后报告。

我尝试过这样的事情:

function crawl(startingSite, depth, callback) {
if (depth < maxDepth) {
    getLinks(startingSite, function (sites) { //pulls all the links from a specific page and returns them as an array of strings
        for (var i = 0; i < sites.length; i++) { //for each string we got from the page
            findTarget(sites[i], depth); //find any of the keywords we want on the page, print out if so
            crawl(sites[i], depth + 1); //crawl all the pages on that page, and increase the depth
        }
    });
}
else
{
    callback();
}
}

但很明显,callback() 会立即被调用,因为爬虫会很快到达深度并退出 if 语句。

只要所有递归实例都完成爬行并达到最大深度,我所需要的就是打印出这个函数(例如到 console.log)。

有什么想法吗?

【问题讨论】:

    标签: javascript node.js asynchronous callback electron


    【解决方案1】:

    你可以使用承诺:

     const links = (start) =>
       new Promise(res => getLinks(start, res));
    
     async function crawl(startingSite, depth) {
        if (depth >= maxDepth) 
          return;
    
       const sites = await links(startingSite);
       for (const site of sites) { 
         await findTarget(site, depth);
         await crawl(site, depth + 1);
       }    
     }
    

    那就这样吧:

      crawl(something, 0).then(() => console.log("done"));
    

    【讨论】:

      猜你喜欢
      • 2012-10-27
      • 1970-01-01
      • 2017-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-11
      • 2019-10-18
      • 1970-01-01
      相关资源
      最近更新 更多