如何递归地调用这个函数

How to call this function recursively?

本文关键字:调用 函数 何递归 递归      更新时间:2023-09-26

我试图想出一个基本的网络爬虫。堆栈跟踪将来要访问的所有url。

在堆栈为空之前,想要获得在网页中使用的所有href的列表。试着用论据。Calee但是它返回:

RangeError: Maximum call stack size exceeded

JavaScript

"checkStack": function(test) {
    //check if the stack is empty
    if (!stack.isEmpty()) {
        var newAddress = stack.pop();
        console.log("trying to navigate to: ", newAddress);
        return test.remote.get(newAddress)
            .setFindTimeout(240000)
            //.sleep(4000)
            .findAllByTagName("a")
            .getAttribute("href")
            .then(function(hrefs) {
                console.log("got hrefs: " + hrefs.length);
                assert.isArray(hrefs, 'Links not an array');
                checkAddressValidity(hrefs, 0);
            })
            .then(function() {
                //call checkStack recursively
                checkStack(test);
            }.bind(test));
    }
},
...

在命令链(或任何承诺链,实际上!)中执行递归的简单方法是将堆栈保持在闭包中,然后作为承诺回调调用递归完成工作的方法,直到堆栈耗尽。一旦堆栈被解析,undefined将由next返回,而不是另一个承诺,这标志着递归的结束:

checkStack: function (test) {
  var remote = test.remote;
  var stack = [];
  function next() {
    var newAddress = stack.pop();
    if (newAddress) {
      return remote.get(newAddress)
        .findAllByTagName('a')
        .getAttribute('href')
        .then(function (hrefs) {
          // do whatever
        })
        .then(next);
    }
  }
  return next();
}