gpt4 book ai didi

javascript - 等待异步递归函数完成,然后再继续执行下一行代码

转载 作者:行者123 更新时间:2023-12-01 01:39:33 26 4
gpt4 key购买 nike

我试图等待递归函数完全完成,然后再继续执行下一行代码。我正在使用 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
}
}

目前,如果第一次尝试时未找到该项目,则会抛出错误并成功开始递归。但是,代码执行会继续,不会等待函数成功完成。

有没有办法让“catch”不解析?我需要从 waitForThisToFinish() 函数返回一个 promise 吗?与递归一起如何工作?任何帮助将不胜感激。

最佳答案

我建议使用一个在成功时退出的循环,因为这样就不会以任何方式(如 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")
}
}
}
<小时/>

此外,您还应该进行一些额外的更改:

  1. 检查实际错误,确保其属于可以通过重试修复的错误类型(例如超时)。如果这是永久性错误,您将永远重试。
  2. 在重试之前实现延迟,以避免在服务器端造成雪崩故障并避免服务器因速率限制而阻塞。
  3. 在延迟中实现渐进式退避。

因为您通常不希望在出现错误时编写对服务器造成影响的代码(通过快速连续地重复发出相同的请求),因为这可能会导致雪崩服务器故障,小问题会变成大问题很快就会出现大问题,您可能应该在再次尝试之前实现延迟,问题持续的时间越长,延迟时间就越长。

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

关于javascript - 等待异步递归函数完成,然后再继续执行下一行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52546720/

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