如何递归调用这个函数?

How to call this function recursively?

我正在尝试开发基本的网络爬虫。堆栈会跟踪将来要访问的所有 URL。

直到堆栈变空,想要获取网页中使用的所有 href 的列表。尝试使用 arguments.calee 但它 returns:

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));

    }
},
...

在 Command 链(或任何 Promise 链,实际上!)中执行递归的简单方法是将堆栈保持在关闭状态,然后以 Promise 回调的形式递归调用执行工作的方法,直到堆栈耗尽.一旦堆栈被解析 undefined 将由 next 返回而不是另一个 promise,这标志着递归的结束:

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();
}