Skip to content

Instantly share code, notes, and snippets.

@mcavaliere
Created August 20, 2020 19:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcavaliere/d332d73edc6146a760daf2d6cc83a431 to your computer and use it in GitHub Desktop.
Save mcavaliere/d332d73edc6146a760daf2d6cc83a431 to your computer and use it in GitHub Desktop.
ESNext Polling Function
/**
* 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