Last active
December 8, 2022 06:28
-
-
Save Phryxia/e98c9d3e9be321843d94d2442ce3013a to your computer and use it in GitHub Desktop.
TypeScript utility which handle promise retrial
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
interface RetryOption { | |
name?: string | |
isintermediateLogged: boolean | |
interval?: number // second | |
maxTries: number | |
} | |
export async function retry<T>( | |
job: () => Promise<T> | T, | |
{ name, isintermediateLogged, interval = 0, maxTries }: RetryOption | |
): Promise<T> { | |
return new Promise<T>((resolve, reject) => { | |
let count = 1 | |
async function retrial() { | |
try { | |
const value = job() | |
if (value instanceof Promise) { | |
resolve(await value) | |
} else { | |
resolve(value) | |
} | |
} catch (e) { | |
console.log(`Retry ${name ?? ''}... (${count}/${maxTries})`) | |
if (isintermediateLogged) { | |
console.log(e) | |
} | |
if (count++ < maxTries) { | |
setTimeout(retrial, 1000 * interval) | |
} else { | |
reject(e) | |
} | |
} | |
} | |
retrial() | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note that single retrial doesn't block stack because each trial is pushed to the event queue, not to the stack directly.
Also, you can give any function with/without
Promise
returned.Example