获取重试请求(失败时) [英] fetch retry request (on failure)
问题描述
我正在使用浏览器的原生获取API 网络请求。此外,我正在为不支持的浏览器使用 whatwg-fetch polyfill。
I'm using browser's native fetch API for network requests. Also I am using the whatwg-fetch polyfill for unsupported browsers.
但是,如果请求失败,我需要重试。现在我找到了这个npm包 whatwg-fetch-retry ,但是他们没有解释如何在他们的文档中使用它。有人可以帮我这个或建议我一个替代方案吗?
However I need to retry in case the request fails. Now there is this npm package whatwg-fetch-retry I found, but they haven't explained how to use it in their docs. Can somebody help me with this or suggest me an alternative?
推荐答案
来自官方提取文档:
fetch('/users')
.then(checkStatus)
.then(parseJSON)
.then(function(data) {
console.log('succeeded', data)
}).catch(function(error) {
console.log('request failed', error)
})
看到那个捕获?将在获取失败时触发,例如,您可以再次获取。
See that catch? Will trigger when fetch fails, you can fetch again there for example.
查看promises https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
Have a look at promises https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
编辑:添加应该返回结果的工作示例。已经尝试过Chrome(v.60.0)并且没有使用任何polyfill,也没有使用你提到的软件包(仔细阅读文档后,它似乎只是来自fetch polifyll的一个分支)。
add working example that should return a result. Have tried in Chrome (v.60.0) and didn't use any polyfill nor the package you mention (after reading carefully the docs it seems its just a fork from fetch polifyll).
function fetchRetry(url, delay, limit, fetchOptions = {}) {
return new Promise((resolve,reject) => {
function success(response) {
resolve(response);
}
function failure(error){
limit--;
if(limit){
setTimeout(fetchUrl,delay)
}
else {
// this time it failed for real
reject(error);
}
}
function finalHandler(finalError){
throw finalError;
}
function fetchUrl() {
return fetch(url,fetchOptions)
.then(success)
.catch(failure)
.catch(finalHandler);
}
fetchUrl();
});
}
fetchRetry('https://www.google.es',1000,4)
.then(function(response){
if(!response.ok){
throw new Error('failed!');
}
return response;
})
.then(function(response){
console.log(response);
})
.catch(function(error){
console.log(error);
});
未测试重试尝试是否返回响应,但我想他们确实如此。
Haven't tested if the retry attempts return the response but I suppose they do.
编辑:发现这个包但它取代了fetch API所以我不太确定, https://www.npmjs.com/package/fetch-retry (在第一个google结果页面中还有两个像这样的包,用于获取重试... )
found this package but it replaces the fetch API so I'm not pretty sure about that, https://www.npmjs.com/package/fetch-retry (there are two more packages like this one in the first google results page for fetch-retry...)
这篇关于获取重试请求(失败时)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!