Created
November 5, 2021 14:21
-
-
Save mikecabana/05770e237b7ef1d82232060aaadb63c9 to your computer and use it in GitHub Desktop.
Generic Polling in Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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