Skip to content

Instantly share code, notes, and snippets.

@spektraldevelopment
Created February 27, 2017 22:42
Show Gist options
  • Save spektraldevelopment/47f1622abdd4a4f63368cce857ad5981 to your computer and use it in GitHub Desktop.
Save spektraldevelopment/47f1622abdd4a4f63368cce857ad5981 to your computer and use it in GitHub Desktop.
JS:fetchRetry
var fetchRetry = (url, attempts) => {
return new Promise((resolve, reject) => {
var wrappedFetch = (triedAttempts) => {
console.log('Try fetch, attempts left: ' + triedAttempts);
fetch(url).then((response) => {
resolve(response);
})
.catch((err) => {
if(triedAttempts > 0) {
setTimeout(() => {
wrappedFetch(--triedAttempts);
}, 1000);
} else {
resolve('Attempts Exceeded, check you connection.');
}
});
};
wrappedFetch(attempts);
});
};
// Example use.
fetchRetry('http://example.com/api.json', 5).then((res) => {
console.log(res);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment