Last active
July 3, 2019 05:36
-
-
Save mkhahani/b9fbb998219c457bf423917f39fc56c5 to your computer and use it in GitHub Desktop.
JavaScript waitFor Promise based utility function
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
/** | |
* Waits specific amount of time for a function to fulfill | |
* @param {number} timeout | |
* @param {function} check | |
* @return {Promise<any>} | |
*/ | |
waitFor: (timeout, check) => new Promise((resolve, reject) => { | |
const timer = setInterval(() => { | |
if (check()) { | |
clearInterval(timer); | |
resolve(); | |
} | |
}, 100); | |
setTimeout(() => { | |
clearInterval(timer); | |
reject(); | |
}, timeout); | |
}), | |
// Usage | |
let variable = false; | |
const check = () => variable; | |
setTimeout(() => { | |
variable = true; | |
}, 3000); | |
waitFor(4000, check) | |
.then(() => { | |
console.log('success'); | |
}) | |
.catch(() => { | |
console.log('failure'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment