Velin Georgiev Blog

Nodejs JavaScript retry logic with fetch

Every time I re-write Nodejs fetch retry logic, this is why I captured it here to have it at hand.


const fetchRetry = async (url, opts) {
let retryFor = 4
let error = "Something went wrong"
const f = async () => {
try {
const resp = await fetch(url, opts)
return [,resp.json()]
} catch (e) {
return [e]
}
}
while(--retryFor) { // 3 times retry
const [err, res] = f()
if(res) return res
console.log('Error')
console.log(e)
console.log('Will retry in 30 sec')
error = err
await new Promise(resolve => setTimeout(resolve, 30000)) //sleep for 30 sec
}
throw new Error(error)
}