Skip to content

Instantly share code, notes, and snippets.

@developit
Created May 8, 2019 22:39
Show Gist options
  • Save developit/a4861ad63081677b7c2945cd39cca8c0 to your computer and use it in GitHub Desktop.
Save developit/a4861ad63081677b7c2945cd39cca8c0 to your computer and use it in GitHub Desktop.
// import fetch from 'isomorphic-unfetch';
const RETRIES = 5;
/**
* Example:
* global.fetch = fetchWithRetry;
*/
function fetchWithRetry(url, options) {
const opts = options || {};
// only retry if the request is GET or HEAD:
if (/(get|head)/i.test(opts.method)) {
return doFetch(url, opts, opts.retries || RETRIES);
}
return fetch(url, opts);
}
function doFetch(url, options, retriesRemaining) {
return fetch(url, options).catch(err => {
if (err.timedout) { // you have to figure out when you want to retry
if (retriesRemaining) {
return doFetch(url, options, retriesRemaining - 1);
}
}
throw err;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment