Last active
August 29, 2015 14:23
-
-
Save wmadden/2d0c68d9901674421673 to your computer and use it in GitHub Desktop.
eventually
This file contains 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
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