gpt4 book ai didi

javascript - 如何递归调用这个函数?

转载 作者:行者123 更新时间:2023-12-03 09:57:23 26 4
gpt4 key购买 nike

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

在堆栈变空之前,想要获取网页中使用的所有 href 的列表。尝试使用arguments.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));

}
},
...

最佳答案

在命令链(实际上是任何 Promise 链!)中执行递归的简单方法是将堆栈保持在闭包中,然后调用作为 Promise 回调递归执行工作的方法,直到堆栈耗尽。一旦堆栈解析完毕,next 将返回 undefined 而不是另一个 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();
}

关于javascript - 如何递归调用这个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30686948/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com