首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在node.js中报告递归函数的完成

在node.js中报告递归函数的完成
EN

Stack Overflow用户
提问于 2018-04-19 03:11:31
回答 1查看 48关注 0票数 0

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

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

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

下面是执行抓取的函数:

代码语言:javascript
运行
复制
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
        }
    });
}
}

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

我尝试了这样的东西:

代码语言:javascript
运行
复制
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 )。

有什么想法吗?

EN

回答 1

Stack Overflow用户

发布于 2018-04-19 03:23:51

你可以使用promises:

代码语言:javascript
运行
复制
 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);
   }    
 }

那就这样做:

代码语言:javascript
运行
复制
  crawl(something, 0).then(() => console.log("done"));
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49907347

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档