Skip to content

Instantly share code, notes, and snippets.

@entrptaher
Forked from sscovil/until.js
Created November 21, 2022 15:28
Show Gist options
  • Save entrptaher/b2a401d05e143c22caa7b28a59714cd4 to your computer and use it in GitHub Desktop.
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.
/**
* 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