Skip to content

Instantly share code, notes, and snippets.

@Jarvis1010
Last active Mar 25, 2021
Embed
What would you like to do?
retry
type PromiseFunc<T> = () => Promise<T>
type Config = {
initialTime?: number
attempts?: number
}
function waitFn<T>(fn: PromiseFunc<T>, time: number): Promise<T> {
return new Promise((r) =>
setTimeout(() => {
r(fn())
}, time),
)
}
function retry<T>(
fn: PromiseFunc<T>,
{ attempts = 10, initialTime = 100 }: Config,
): PromiseFunc<T> {
const retries = [...Array(attempts).keys()]
.reduce((arr) => arr.concat(arr[arr.length - 1] * 2), [1])
.map((x) => x * initialTime)
return () =>
retries.reduce((promise, time) => promise.catch(() => wait(fn, time)), fn())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment