Created
December 9, 2017 18:06
-
-
Save midnightcodr/154896cc45f6aa5eb53be51709abb5d7 to your computer and use it in GitHub Desktop.
node-fetch with retry
This file contains 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 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