Skip to content

Instantly share code, notes, and snippets.

@raphaeladrien
Last active May 24, 2018 09:41
Show Gist options
  • Save raphaeladrien/51c6f39c0c14a51f17fff93e9cb22f5a to your computer and use it in GitHub Desktop.
Save raphaeladrien/51c6f39c0c14a51f17fff93e9cb22f5a to your computer and use it in GitHub Desktop.
export const retryFetch = (url, options, retryConf = {maxRetries: 2, delay: 200}) => {
return new Promise((resolve, reject) => {
const wrappedFetch = ({maxRetries, delay}) => {
fetch(url, options)
.then(response => {
const status = response.status
if (status >= 500) {
if (maxRetries > 0) {
retry(maxRetries, delay)
} else {
reject(new ServerRequestError(response))
}
} else {
resolve(response)
}
})
.catch((error) => {
if (maxRetries > 0) {
retry(maxRetries, delay)
} else {
reject(error)
}
})
}
const retry = (max, delay) => {
setTimeout(() => {
wrappedFetch({ maxRetries: --max, delay: delay * 2 })
}, delay)
}
wrappedFetch(retryConf)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment