Created
August 18, 2018 15:43
-
-
Save phil-kahrl/e33c1596e10f530e99b0b498da93a83e to your computer and use it in GitHub Desktop.
Recursive fetch with retry and delay
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) | |
setTimeout( () => fetchWithRetry(resolve, reject, attemptCount), 1000) | |
}) | |
} | |
}) | |
} | |
fetchWithRetry() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment