Created
August 20, 2020 19:06
-
-
Save mcavaliere/d332d73edc6146a760daf2d6cc83a431 to your computer and use it in GitHub Desktop.
ESNext Polling Function
This file contains hidden or 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
/** | |
* Run an async function repeatedly until a condition is met, or we hit a max # of attempts. | |
* | |
* @param {Number} maxAttempts - Max # of times to run iterate() before we quit. | |
* @param {Number} frequency - # milliseconds to wait in between attempts. | |
* @param {Function} iterate - Async. Code to run on every iteration. | |
* @param {Function} check - Accepts iterate response, return true/false if success criteria are met. | |
* @param {Function} onSuccess - Success callback. | |
* @param {Function} onMaxAttemptsExceeded - Failure callback. | |
*/ | |
export const tryUntil = async ({ | |
maxAttempts = 5, | |
frequency = 1000, | |
// What do do on each iteration. Returns any params required for check(). | |
iterate = () => {}, | |
// Take any params returned from iterate(); return true if we're done, false to iterate again. | |
check = () => {}, | |
onSuccess = () => {}, | |
onMaxAttemptsExceeded = () => {} | |
}) => { | |
let attempts = 0; | |
const interval = setInterval(async () => { | |
const response = await iterate(); | |
if (check(response)) { | |
onSuccess(response); | |
clearInterval(interval); | |
return | |
} | |
// Max # of attempts exceeded | |
attempts += 1; | |
if(attempts >= maxAttempts) { | |
onMaxAttemptsExceeded(response); | |
clearInterval(interval); | |
} | |
}, frequency) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment