Created
February 19, 2020 09:16
-
-
Save markmur/172e4841c63beb961ef07811526de366 to your computer and use it in GitHub Desktop.
TypeScript retry util helper
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 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