Last active
February 11, 2022 08:36
-
-
Save phil-kahrl/565bc9b7649de2414396de5a6e3712e2 to your computer and use it in GitHub Desktop.
Fetch with retry
This file contains hidden or 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
const fetch = require('node-fetch'); | |
const MAX_RETRIES = 5 | |
const fetchWithRetry = (origResolve, origReject, attemptCount) => { | |
attemptCount = attemptCount ? attemptCount : 0 | |
const url = process.argv[2] | |
if(!url){ | |
console.log('no url passed in') | |
return | |
} | |
return new Promise( (resolve, reject) => { | |
attemptCount++ | |
console.log(`attempt ${attemptCount}`) | |
if(attemptCount > MAX_RETRIES) { | |
reject('max retries exceeded') | |
} else { | |
// The resolve and reject function references will be passed down the call stack. | |
resolve = (origResolve) ? origResolve : resolve | |
reject = (origReject) ? origReject : reject | |
fetch(url, {method: 'get'}).then( (result) => { | |
console.log('success') | |
resolve() | |
}).catch( (error) => { | |
console.log(error) | |
fetchWithRetry(resolve, reject, attemptCount) | |
}) | |
} | |
}) | |
} | |
fetchWithRetry() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment