Created
February 27, 2017 22:42
-
-
Save spektraldevelopment/47f1622abdd4a4f63368cce857ad5981 to your computer and use it in GitHub Desktop.
JS:fetchRetry
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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