Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const fetchWithRetry = (userOptions) => {
- let abort = false;
- const options = {
- url: '',
- options: {},
- cancel: {},
- retries: 3,
- retryDelay: 1000,
- ...userOptions
- };
- // Add an abort to the cancel object.
- if(!cancel.abort) cancel.abort = () => { abort = true };
- // Abort or proceed?
- return abort ? Promise.reject('aborted') : fetch(options.url).then(response => {
- // Reject because of abort
- return abort ? Promise.reject('aborted')
- // Response is good
- : response.ok ? Promise.resolve(response.text())
- // Retries exceeded
- : !options.retries ? Promise.reject('retries exceeded')
- // Retry with one less retry
- : new Promise((resolve, reject){
- setTimeout(() => {
- // We use the returned promise's resolve and reject as
- // callback so that the nested call propagates backwards.
- fetchWithRetry({ ...options, retries: retries - 1 }).then(resolve, reject);
- }, options.retryDelay);
- });
- });
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement