Created
December 31, 2019 16:14
-
-
Save treyhuffine/a13f598d1466240de0d896e7efbe753b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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