Skip to content

Instantly share code, notes, and snippets.

@sscovil
Created February 20, 2018 19:30
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sscovil/6502c72de3e24232f66b5bf86de04680 to your computer and use it in GitHub Desktop.
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.
/**
* 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;
@tomlarkworthy
Copy link

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment