Created
June 25, 2018 16:30
-
-
Save zucchinidev/3038db8bd83791b6a0a8d8b69360ef7c to your computer and use it in GitHub Desktop.
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
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