-
Notifications
You must be signed in to change notification settings - Fork 4
/
until.ts
36 lines (34 loc) · 1.08 KB
/
until.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import type { BaseRetryOption } from './type';
import delay from './delay';
import isFunction from '../is/is-Function';
/**
* promise resolve 没有值的情况重试,每次失败reject都会报错
* 一定次数内重试获取获取一些异步的值
* @param fn
* @param retryOption
* @category Promise
*/
function until<T extends (...args: any[]) => Promise<any>>(fn: T, retryOption: BaseRetryOption): T {
return (async (...args: any[]): Promise<any> => {
let retries = retryOption.maxAttempts!;
let attempts = 0;
while (retries !== undefined ? retries : true) {
if (retries !== undefined) {
--retries;
}
++attempts;
const result = await fn(...args);
if (result) {
return result;
}
if (retryOption.delayMs) {
const delayMs = isFunction(retryOption.delayMs)
? retryOption.delayMs(attempts) || 0
: retryOption.delayMs;
await delay(delayMs);
}
}
throw new Error(`Could not complete function within ${retryOption.maxAttempts} attempts`);
}) as T;
}
export default until;