Last active
May 24, 2018 09:41
-
-
Save raphaeladrien/51c6f39c0c14a51f17fff93e9cb22f5a to your computer and use it in GitHub Desktop.
This file contains 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
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