Skip to content

Instantly share code, notes, and snippets.

@midnightcodr
Created December 9, 2017 18:06
Show Gist options
  • Save midnightcodr/154896cc45f6aa5eb53be51709abb5d7 to your computer and use it in GitHub Desktop.
Save midnightcodr/154896cc45f6aa5eb53be51709abb5d7 to your computer and use it in GitHub Desktop.
node-fetch with retry
const fetch = require('node-fetch')
const delay = (ms) => {
return new Promise(resolve => {
setTimeout(() => {
resolve()
}, ms)
})
}
const retryFetch = (url, fetchOptions={}, retries=3, retryDelay=1000) => {
return new Promise((resolve, reject) => {
const wrapper = n => {
fetch(url, fetchOptions)
.then(res => { resolve(res) })
.catch(async err => {
if(n > 0) {
// console.log(`retrying ${n}`)
await delay(retryDelay)
wrapper(--n)
} else {
reject(err)
}
})
}
wrapper(retries)
})
}
retryFetch('http://localhost:8080/test', {}, 20)
.then(res => res.text())
.then(console.log)
.catch(console.error)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment