Skip to content

Instantly share code, notes, and snippets.

@zucchinidev
Created June 25, 2018 16:30
Show Gist options
  • Save zucchinidev/3038db8bd83791b6a0a8d8b69360ef7c to your computer and use it in GitHub Desktop.
Save zucchinidev/3038db8bd83791b6a0a8d8b69360ef7c to your computer and use it in GitHub Desktop.
export class RetryRequest {
private maxRetries: number[];
constructor(private timeout: number, maxRetries = 10) {
this.maxRetries = [...Array(maxRetries)].map((_, i) => i)
}
wait(timeout: number) {
return new Promise((resolve) => setTimeout(() => resolve(), timeout))
}
async requestWithRetry(url: string) {
for (const i of this.maxRetries) {
try {
const response = await fetch(url)
return response.json()
} catch (err) {
console.log('Waiting', this.timeout, 'ms')
await this.wait(this.timeout)
console.log('Retrying', err.message, i)
}
}
}
}
const url = 'https://jsonplaceholder.typicode.com/posts/1';
new RetryRequest(2000).requestWithRetry(url);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment