-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
index.js
55 lines (45 loc) · 1.21 KB
/
index.js
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import pTimeout from 'p-timeout';
const resolveValue = Symbol('resolveValue');
export default async function pWaitFor(condition, options = {}) {
const {
interval = 20,
timeout = Number.POSITIVE_INFINITY,
before = true,
} = options;
let retryTimeout;
let abort = false;
const promise = new Promise((resolve, reject) => {
const check = async () => {
try {
const value = await condition();
if (typeof value === 'object' && value[resolveValue]) {
resolve(value[resolveValue]);
} else if (typeof value !== 'boolean') {
throw new TypeError('Expected condition to return a boolean');
} else if (value === true) {
resolve();
} else if (!abort) {
retryTimeout = setTimeout(check, interval);
}
} catch (error) {
reject(error);
}
};
if (before) {
check();
} else {
retryTimeout = setTimeout(check, interval);
}
});
if (timeout === Number.POSITIVE_INFINITY) {
return promise;
}
try {
return await pTimeout(promise, typeof timeout === 'number' ? {milliseconds: timeout} : timeout);
} finally {
abort = true;
clearTimeout(retryTimeout);
}
}
pWaitFor.resolveWith = value => ({[resolveValue]: value});
export {TimeoutError} from 'p-timeout';