Skip to content

Instantly share code, notes, and snippets.

@Sixl-Daniel
Forked from treyhuffine/poll.js
Created December 9, 2020 18:10
Show Gist options
  • Save Sixl-Daniel/1c9b8803449d6b810858e50f5fef16cb to your computer and use it in GitHub Desktop.
Save Sixl-Daniel/1c9b8803449d6b810858e50f5fef16cb 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