Created
May 30, 2022 11:58
-
-
Save employee451/9441d4777ed1826960e6388613d7ffde to your computer and use it in GitHub Desktop.
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
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