Skip to content

Instantly share code, notes, and snippets.

@markmur
Created February 19, 2020 09:16
Show Gist options
  • Save markmur/172e4841c63beb961ef07811526de366 to your computer and use it in GitHub Desktop.
Save markmur/172e4841c63beb961ef07811526de366 to your computer and use it in GitHub Desktop.
TypeScript retry util helper
export interface RetryConfig {
timeout: number
max: number
}
export const retryAction = (
fn: (...args: any[]) => Promise<any>,
{ timeout, max }: RetryConfig
): Promise<any | void> => {
// Keep a count of the retries
let retries = max
/* tslint:disable */
const AsyncFunction = (async () => {}).constructor
/* tslint:enable */
// Fail silently if fn is not an async function
if (!(fn instanceof AsyncFunction)) {
return Promise.resolve()
}
return new Promise(resolve => {
function exec() {
// If the call fails, re-execute after
setTimeout(async () => {
try {
resolve(await fn())
} catch (error) {
// Decrement the number of retries
retries--
if (retries > 0) {
return exec()
} else {
// Resolve gracefully
return resolve(undefined)
}
}
}, timeout)
}
return exec()
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment