Skip to content

Instantly share code, notes, and snippets.

@phil-kahrl
Last active February 11, 2022 08:36
Show Gist options
  • Save phil-kahrl/565bc9b7649de2414396de5a6e3712e2 to your computer and use it in GitHub Desktop.
Save phil-kahrl/565bc9b7649de2414396de5a6e3712e2 to your computer and use it in GitHub Desktop.
Fetch with retry
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