gpt4 book ai didi

javascript - 重试 promise 直到解决(递归错误太多)

转载 作者:行者123 更新时间:2023-11-28 12:13:54 25 4
gpt4 key购买 nike

我试图测试我是否可以重试 promise ,直到它解决,但它不断给出“太多递归”错误,我不明白为什么它在第三次递归后没有停止。

以下代码尝试模拟对服务器的失败查询请求,该请求来自非 promise 函数。

function nonPromiseCallback(x, resolve, reject){    
if(x < 3){
reject(x)
}else{
resolve(x)
}
}

function tryUntilThree(x){
return new Promise( (resolve, reject) => {
nonPromiseCallback(x, resolve, tryUntilThree(x+1));
})
}

tryUntilThree(1)
.then(console.log);

最佳答案

由于您对 promise 失败感兴趣,因此可以使用 catch 处理程序。

至于为什么你的代码不起作用,some 给出了很好的解释。 (也在评论中):

You get too much recursion because tryUntilThree is called too many times. Notice that you have written tryUntilThree(x+1), ie the engine has to resolve the call to tryUntilThree before it can call nonPromiseCallback. You have an infinite loop there.

function nonPromiseCallback(x, resolve, reject){    
if(x < 3){
reject(x)
}else{
resolve(x)
}
}

function tryUntilThree(x){
return new Promise( (resolve, reject) =>
nonPromiseCallback(x, resolve, reject)
).catch(() =>
tryUntilThree(x + 1)
)
}

tryUntilThree(1)
.then(console.log);

关于javascript - 重试 promise 直到解决(递归错误太多),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54254568/

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