-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
27 lines (26 loc) · 811 Bytes
/
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
function getGlobal() {
if (typeof globalThis !== 'undefined') { return globalThis; }
if (typeof self !== 'undefined') { return self; }
if (typeof window !== 'undefined') { return window; }
if (typeof global !== 'undefined') { return global; }
throw new Error('unable to locate global object');
}
module.exports = function awaitGlobal(key, wait, maxAttempts) {
const root = getGlobal();
let attempts = maxAttempts || 3;
return new Promise((resolve, reject) => {
let timer;
const loop = () => {
attempts--;
if(root[key]) {
resolve(root[key]);
clearInterval(timer);
} else if (!attempts) {
reject(new Error('Too many attempts'));
clearInterval(timer);
}
};
timer = setInterval(loop, wait || 300);
loop();
});
};