feat(util): add retry function
This commit is contained in:
parent
09dbac1aa2
commit
bfc44bc7b5
1 changed files with 25 additions and 0 deletions
25
src/utils/func.ts
Normal file
25
src/utils/func.ts
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
const MAX_RETRY = 3;
|
||||
|
||||
/**
|
||||
* @param func - Function to do.
|
||||
* @param cond - Retry condition callback function. Stop when the function return false,
|
||||
*/
|
||||
export async function retry<T extends () => any>(
|
||||
func: T,
|
||||
cond = (error: any) => !!error,
|
||||
): Promise<ReturnType<T>> {
|
||||
let retries = 0;
|
||||
|
||||
while (retries++ < MAX_RETRY - 1) {
|
||||
try {
|
||||
return await func();
|
||||
} catch (error) {
|
||||
if (cond(error)) {
|
||||
retries++;
|
||||
continue;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
return func();
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue