[英]Wait for async recursive function to complete before proceeding to next line of code
我正在尝试等待递归函数完全完成,然后再继续执行下一行代码。 我正在使用PuppeteerJS在页面上查找项目,如果该项目不存在,请在3秒钟后重新加载页面,然后重试。 在继续之前,我需要完成此功能。 下面是我要实现的简单代码示例。
(async () => {
await waitForThisToFinish() // Wait for this function no matter how long it takes
console.log("Don't log until function has completed")
})()
async function waitForThisToFinish() {
try {
await findItemOnPage() //function times out after 3 seconds
}
catch (ex) {
// If Item is not found after 3 seconds an error is thrown.
// Catch error and reload page to see if item has been loaded and look again.
waitForThisToFinish() //recursive call
}
}
当前,如果在第一次尝试中未找到该项目,则会引发错误,并且递归成功启动。 但是,代码执行将继续,并且不会等待功能成功完成。
有没有办法使“抓住”解决? 我是否需要从waitForThisToFinish()函数返回承诺? 递归将如何工作? 任何帮助,将不胜感激。
我建议您使用一个在成功时就中断的循环,因为这样就不会以任何方式积累资源(例如promise),并且如果需要,您可以无限次调用函数,而无需强调资源的使用。
async function waitForThisToFinish() {
while (true) {
try {
let val = await findItemOnPage()
// use break or return here to break out of the loop
return val;
} catch (ex) {
console.log("still waiting and trying again")
}
}
}
此外,您还应该进行其他一些更改:
由于您通常不希望在发生错误时编写会锤打服务器的代码(通过快速连续不断地反复提出相同的请求),因为这可能会导致雪崩服务器故障,从而使小问题变成大问题很快,您可能应该实施一个延迟,然后再试一次;如果问题持续存在的时间越长,则延迟时间越长。
function delay(t) {
return new Promise(resolve => {
setTimeout(resolve, t);
});
}
async function waitForThisToFinish() {
let waitTime = 100;
while (true) {
try {
let val = await findItemOnPage()
// use break or return here to break out of the loop
return val;
} catch (ex) {
// Should also check if the actual error is one that is likely
// temporary. Otherwise, you may loop forever on a permanent error
console.log("still waiting and trying again")
// implement super simple backoff (there are much more elegant algorithms available)
await delay(waitTime);
waitTime += 300;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.