I'm using browser's native fetch API for network requests. Also I am using the whatwg-fetch polyfill for unsupported browsers.
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?
From the official fetch docs :
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.
Have a look at promises https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
Edit: 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.
Edit: 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...)
I recommend using some library for promise retry, for example p-retry.
Example:
const pRetry = require('p-retry')
const fetch = require('node-fetch')
async function fetchPage () {
const response = await fetch('https://stackoverflow.com')
// Abort retrying if the resource doesn't exist
if (response.status === 404) {
throw new pRetry.AbortError(response.statusText)
}
return response.blob()
}
;(async () => {
console.log(await pRetry(fetchPage, {retries: 5}))
})()
来源:https://stackoverflow.com/questions/46175660/fetch-retry-request-on-failure