Guest User

Untitled

a guest
May 27th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.88 KB | None | 0 0
  1. export const retryFetch = (url, options, retryConf = {maxRetries: 2, delay: 200}) => {
  2. return new Promise((resolve, reject) => {
  3. const wrappedFetch = ({maxRetries, delay}) => {
  4. fetch(url, options)
  5. .then(response => {
  6. const status = response.status
  7. if (status >= 500) {
  8. if (maxRetries > 0) {
  9. retry(maxRetries, delay)
  10. } else {
  11. reject(new ServerRequestError(response))
  12. }
  13. } else {
  14. resolve(response)
  15. }
  16. })
  17. .catch((error) => {
  18. if (maxRetries > 0) {
  19. retry(maxRetries, delay)
  20. } else {
  21. reject(error)
  22. }
  23. })
  24. }
  25.  
  26. const retry = (max, delay) => {
  27. setTimeout(() => {
  28. wrappedFetch({ maxRetries: --max, delay: delay * 2 })
  29. }, delay)
  30. }
  31.  
  32. wrappedFetch(retryConf)
  33. })
  34. }
Add Comment
Please, Sign In to add comment