Created
June 3, 2019 13:11
-
-
Save bbars/40c2fc9ec2157675c167973d2a75f8c4 to your computer and use it in GitHub Desktop.
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
Function.prototype.expectResult = async function expectResult(interval, timeout, expectValue) { | |
if (interval <= 0) | |
interval = 1000; | |
var fn = this; | |
var timeStart = Date.now(); | |
var tries = 0; | |
function check() { | |
var value, error, asExpected; | |
try { | |
value = fn(); | |
} | |
catch (e) { | |
error = e; | |
} | |
if (typeof expectValue === 'function') | |
asExpected = expectValue(value); | |
else if (typeof expectValue === 'boolean') | |
asExpected = !!value == !!expectValue; | |
else | |
asExpected = value == expectValue; | |
return { | |
tries: ++tries, | |
value: value, | |
timeStart: timeStart, | |
time: Date.now() - timeStart, | |
asExpected: asExpected, | |
error: error, | |
}; | |
} | |
return new Promise(function (resolve, reject) { | |
function retry() { | |
var res = check(); | |
if (timeout > 0 && !res.error && res.time > timeout) { | |
res.error = new Error("Timeout"); | |
} | |
if (res.asExpected) { | |
resolve(res); | |
} | |
else if (res.error) { | |
reject(res); | |
} | |
else { | |
setTimeout(retry, interval); | |
} | |
} | |
retry(); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment