Skip to content

Instantly share code, notes, and snippets.

@employee451
Created May 30, 2022 11:58
Show Gist options
  • Save employee451/9441d4777ed1826960e6388613d7ffde to your computer and use it in GitHub Desktop.
Save employee451/9441d4777ed1826960e6388613d7ffde to your computer and use it in GitHub Desktop.
type RetrierResponseType<DataType> =
| {
success: false
data?: any
}
| {
success: true
data: DataType
}
/**
* Retry an asynchronous function.
* @param fn Function to retry
* @param times Amount of times to retry before giving up
* @param determiner Function that determines whether the attempt was successfull (optional)
*/
async function retrier<ResponseType = any>(
fn: () => Promise<ResponseType>,
times = 3,
determiner?: (data: ResponseType) => boolean
): Promise<RetrierResponseType<ResponseType>> {
for (let i = 0; i < times; i++) {
try {
const response = await fn()
// Fail if there is a determiner, the determiner fails, and we have no more times left to try
if (!!determiner && !determiner(response) && i + 1 === times) {
console.error(response)
return {
success: false,
data: response,
}
}
return {
success: true,
data: response,
}
} catch (error) {
if (i + 1 === times) {
console.error(error)
return {
success: false,
data: error,
}
}
}
}
return {
success: false,
}
}
export default retrier
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment