gpt4 book ai didi

javascript - 获取重试请求(失败时)

转载 作者:数据小太阳 更新时间:2023-10-29 06:09:46 24 4
gpt4 key购买 nike

我正在使用浏览器的 native fetch API对于网络请求。我也在使用 whatwg-fetch用于不支持的浏览器的 polyfill。

但是,如果请求失败,我需要重试。现在有这个 npm 包 whatwg-fetch-retry我找到了,但他们没有在他们的文档中解释如何使用它。有人可以帮我解决这个问题或建议我替代方案吗?

最佳答案

来自获取文档:

fetch('/users')
.then(checkStatus)
.then(parseJSON)
.then(function(data) {
console.log('succeeded', data)
}).catch(function(error) {
console.log('request failed', error)
})

看到那个渔获物了吗? fetch失败时会触发,可以在那里重新fetch。看看 Promise API。

实现示例:

function wait(delay){
return new Promise((resolve) => setTimeout(resolve, delay));
}

function fetchRetry(url, delay, tries, fetchOptions = {}) {
function onError(err){
triesLeft = tries - 1;
if(!triesLeft){
throw err;
}
return wait(delay).then(() => fetchRetry(url, delay, triesLeft, fetchOptions));
}
return fetch(url,fetchOptions).catch(onError);
}

编辑 1:as suggested by golopot , p-retry 是一个不错的选择。

编辑 2:简化示例代码。

关于javascript - 获取重试请求(失败时),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46175660/

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