gpt4 book ai didi

javascript - 有什么方法可以发出递归获取请求吗?

转载 作者:太空宇宙 更新时间:2023-11-04 03:24:25 24 4
gpt4 key购买 nike

如果基于响应的 HTTP 代码(例如:不是 200),我希望我的获取请求有某种重试系统,如果它因某种原因失败。它看起来像这样:

fetch('someURLWithAJSONfile/file.json')
.then(function (res) {
console.log(res.status);
if (res.status !== 200) {
console.log("There was an error processing your fetch request. We are trying again.");

// Recursive call to same fetch request until succeeds

} else {
return res.json();
}
}).then(function (json) {
data = json;
}).catch(function (err) {
console.log(`There was a problem with the fetch operation: ${err.message}`);
});

有没有办法将获取请求放入自定义 Promise 中,并使其在检查其 http 响应状态后调用自身?

最佳答案

这里是简单的 ES6 解决方案(因为您使用的是 fetch)。 limit 选项表示您想要尝试请求的次数。

var doRecursiveRequest = (url, limit = Number.MAX_VALUE) => 
fetch(url).then(res => {
if (res.status !== 200 && --limit) {
return doRecursiveRequest(url, limit);
}
return res.json();
});

doRecursiveRequest('someURLWithAJSONfile/file.json', 10)
.then(data => console.log(data))
.catch(error => console.log(error));

关于javascript - 有什么方法可以发出递归获取请求吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46409024/

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