Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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)
- })
- }
Add Comment
Please, Sign In to add comment