Created
February 20, 2018 19:30
-
-
Save sscovil/6502c72de3e24232f66b5bf86de04680 to your computer and use it in GitHub Desktop.
A simple utility for Node.js to wait until a predicate function returns truthy before moving on; for use with ES6 async/await syntax.
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
/** | |
* Utility that waits for @predicate function to return truthy, testing at @interval until @timeout is reached. | |
* | |
* Example: await until(() => spy.called); | |
* | |
* @param {Function} predicate | |
* @param {Number} interval | |
* @param {Number} timeout | |
* | |
* @return {Promise} | |
*/ | |
async function until(predicate, interval = 500, timeout = 30 * 1000) { | |
const start = Date.now(); | |
let done = false; | |
do { | |
if (predicate()) { | |
done = true; | |
} else if (Date.now() > (start + timeout)) { | |
throw new Error(`Timed out waiting for predicate to return true after ${timeout}ms.`); | |
} | |
await new Promise((resolve) => setTimeout(resolve, interval)); | |
} while (done !== true); | |
} | |
module.exports = until; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
love it! If you put your own attribution in the comment it would be a single copy and paste to use and attribute in my source code!