Advertisement
Guest User

Untitled

a guest
Apr 21st, 2017
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.01 KB | None | 0 0
  1. const fetchWithRetry = (userOptions) => {
  2. let abort = false;
  3. const options = {
  4. url: '',
  5. options: {},
  6. cancel: {},
  7. retries: 3,
  8. retryDelay: 1000,
  9. ...userOptions
  10. };
  11.  
  12. // Add an abort to the cancel object.
  13. if(!cancel.abort) cancel.abort = () => { abort = true };
  14.  
  15. // Abort or proceed?
  16. return abort ? Promise.reject('aborted') : fetch(options.url).then(response => {
  17.  
  18. // Reject because of abort
  19. return abort ? Promise.reject('aborted')
  20.  
  21. // Response is good
  22. : response.ok ? Promise.resolve(response.text())
  23.  
  24. // Retries exceeded
  25. : !options.retries ? Promise.reject('retries exceeded')
  26.  
  27. // Retry with one less retry
  28. : new Promise((resolve, reject){
  29. setTimeout(() => {
  30.  
  31. // We use the returned promise's resolve and reject as
  32. // callback so that the nested call propagates backwards.
  33. fetchWithRetry({ ...options, retries: retries - 1 }).then(resolve, reject);
  34. }, options.retryDelay);
  35.  
  36. });
  37. });
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement