-
-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathpolling function
More file actions
19 lines (17 loc) · 680 Bytes
/
polling function
File metadata and controls
19 lines (17 loc) · 680 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
async function poll(fn, validate, interval = 2500) {
const resolver = async (resolve, reject) => {
try { // catch any error thrown by the "fn" function
const result = await fn(); // fn does not need to be asynchronous or return promise
// call validator to see if the data is at the state to stop the polling
const valid = validate(result);
if (valid === true) {
resolve(result);
} else if (valid === false) {
setTimeout(resolver, interval, resolve, reject);
} // if validator returns anything other than "true" or "false" it stops polling
} catch (e) {
reject(e);
}
};
return new Promise(resolver);
}