-
-
Save entrptaher/b2a401d05e143c22caa7b28a59714cd4 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