Skip to content

Instantly share code, notes, and snippets.

@treyhuffine
Created December 31, 2019 16:14
Show Gist options
  • Save treyhuffine/a13f598d1466240de0d896e7efbe753b to your computer and use it in GitHub Desktop.
Save treyhuffine/a13f598d1466240de0d896e7efbe753b to your computer and use it in GitHub Desktop.
const poll = async ({ fn, validate, interval, maxAttempts }) => {
let attempts = 0;
const executePoll = async (resolve, reject) => {
const result = await fn();
attempts++;
if (validate(result)) {
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