抛出错误时如何在循环中重试获取 [英] How to retry fetch in a loop when it throws an error
本文介绍了抛出错误时如何在循环中重试获取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下JS函数:
func() {
return fetch({
...
}).then({
...
})catch({
...
})
}
在其中我返回由 fetch()
返回的承诺.万一它失败了(即调用 catch()
块),我想重复一遍.有点像把整个东西放在 while(true)
循环中,但是我不知道如何用promises来做到这一点.
In it I return a promise returned by fetch()
. In the event that it fails (ie calls catch()
block) I want to repeat the whole thing. Something like having the whole thing in a while (true)
loop, but I can't figure out how to do this with promises.
有什么建议吗?
推荐答案
您应该仔细查看Promise和异步等待.
you should have a close look to promises and async await.
async function fetchUntilSucceeded() {
let success = false;
while(!success) {
try {
let result = await fetch(...);
success = true;
//do your stuff with your result here
} catch {
//do your catch stuff here
}
}
}
如果您只需要结果:
async function fetchUntilSucceeded() {
while(true) {
try {
return await fetch(...);
}
}
}
但是请谨慎使用此类代码,因为它可能永远无法解决!而且它可以发送很多请求,而无需等待时间.
But be careful with such code as it might never resolve! also it can send a lot of requests without any waittime in between.
这篇关于抛出错误时如何在循环中重试获取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文