Skip to content

Instantly share code, notes, and snippets.

@mikecabana
Created November 5, 2021 14:21
Show Gist options
  • Save mikecabana/05770e237b7ef1d82232060aaadb63c9 to your computer and use it in GitHub Desktop.
Save mikecabana/05770e237b7ef1d82232060aaadb63c9 to your computer and use it in GitHub Desktop.
Generic Polling in Javascript
// curtesy of this post https://levelup.gitconnected.com/polling-in-javascript-ab2d6378705a
const poll = async ({ fn, validate, interval, maxAttempts }) => {
let attempts = 0;
const executePoll = async (resolve, reject) => {
const result = await fn();
attempts++;
const validationResult = await validate(result);
if (validationResult) {
return resolve(result);
} else if (maxAttempts && attempts === maxAttempts) {
return reject(new Error('Exceeded max attempts'));
} else {
setTimeout(executePoll, interval, resolve, reject);
}
};
return new Promise(executePoll);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment