-
-
Save oirodolfo/ac18281a0255812bb9ded217e1f605a2 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