Last active
April 27, 2018 10:19
-
-
Save andreasvirkus/5b56b9d65b0b0ef8f07d4a161a9a4472 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
// The polling function | |
function poll(fn, condition) { | |
const endTime = Number(new Date()) + timeout | |
const checkCondition = (resolve, reject) => fn() | |
.then(response => { | |
if (condition(response)) { | |
resolve(response) | |
} else if (Number(new Date()) < endTime) { | |
// Condition isn't met but the timeout hasn't elapsed, go again | |
setTimeout(checkCondition, interval, resolve, reject) | |
} else { | |
// Didn't match and too much time passed, reject! | |
reject(new Error(`Polling timed out for function::\n\t${fn}`)) | |
} | |
}).catch(err => reject(err)) | |
return new Promise(checkCondition) | |
} | |
// Using | |
function runner() { | |
const queryStatus = () => axios.get('/api/', payload) | |
return poll(queryStatus, res => res.data.nextStep) | |
.then(res => res.data) | |
.then(res => { | |
// Do great stuff | |
}) | |
.catch(err => console.error('tsk-tsk-tsk', err)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment