Created
November 19, 2020 04:28
-
-
Save casschin/c49fad36df21c602b14f1444ab3292bd to your computer and use it in GitHub Desktop.
polling function with the ability to cancel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function poll({ fn, validate, interval = 1000, maxAttempts = 100 }) { | |
let attempts = 0; | |
let stop = false; | |
async function execute(resolve, reject) { | |
const res = await fn(); | |
attempts += 1; | |
if (validate(res)) { | |
resolve(res); | |
} else if (maxAttempts === attempts) { | |
return reject("Hit max poll attempts"); | |
} else if (!stop) { | |
setTimeout(execute, interval, resolve, reject); | |
} | |
} | |
function clear() { | |
stop = true; | |
} | |
return [new Promise(execute), clear]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment