Skip to content

Instantly share code, notes, and snippets.

@jpcaparas
Created December 6, 2021 20:24
Show Gist options
  • Save jpcaparas/9faa2feaff8ff8da1f4086980e0b0b84 to your computer and use it in GitHub Desktop.
Save jpcaparas/9faa2feaff8ff8da1f4086980e0b0b84 to your computer and use it in GitHub Desktop.
Polling
// https://levelup.gitconnected.com/polling-in-javascript-ab2d6378705a
export default const poll = ({ fn, validate, interval, maxAttempts }) => {
console.log('Start poll...');
let attempts = 0;
const executePoll = async (resolve, reject) => {
console.log('- poll');
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);
};
@jpcaparas
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment