Skip to content

Instantly share code, notes, and snippets.

@bbars
Created June 3, 2019 13:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bbars/40c2fc9ec2157675c167973d2a75f8c4 to your computer and use it in GitHub Desktop.
Save bbars/40c2fc9ec2157675c167973d2a75f8c4 to your computer and use it in GitHub Desktop.
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