Skip to content

Instantly share code, notes, and snippets.

@wmadden
Last active August 29, 2015 14:23
Show Gist options
  • Save wmadden/2d0c68d9901674421673 to your computer and use it in GitHub Desktop.
Save wmadden/2d0c68d9901674421673 to your computer and use it in GitHub Desktop.
eventually
var MAX_TIME_TO_WAIT = 10; // ms
// Tests for the eventual satisfaction of a set of expectations. Returns
// a Promise that resolves if the given function runs without errors and
// rejects if resolution cannot be obtained within `MAX_TIME_TO_WAIT` ms.
function eventually(expectations) {
var timeStarted = Date.now();
new Promise(function (resolve, reject) {
function testExpectationsAndResolve() {
try {
expectations();
resolve(); // Resolve if no exception is thrown
} catch (error) {
var timeSpent = Date.now() - timeStarted;
if (timeSpent > MAX_TIME_TO_WAIT) {
// Pass along the error if we've timed out
reject(error);
} else {
// Otherwise try again
setTimeout(testExpectationsAndResolve);
}
}
}
setTimeout(testExpectationsAndResolve);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment