rc-js-util
Version:
A collection of TS and C++ utilities to help writing performant and correct applications, achieved through strict typing and (removable) invariant checking.
55 lines • 1.99 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.promisePoll = exports.EResolutionState = void 0;
const fp_identity_js_1 = require("../../fp/impl/fp-identity.js");
/**
* @public
*/
var EResolutionState;
(function (EResolutionState) {
EResolutionState[EResolutionState["Resolved"] = 0] = "Resolved";
EResolutionState[EResolutionState["TimedOut"] = 1] = "TimedOut";
EResolutionState[EResolutionState["Cancelled"] = 2] = "Cancelled";
})(EResolutionState || (exports.EResolutionState = EResolutionState = {}));
/**
* @public
* @param predicate - Once true, the poll finishes. Exceptions are not supported.
* @param pollInterval - In milliseconds, defaults to smallest (probably 4 ms).
* @param maxTicks - The number of times to run the poll before giving up.
*/
function promisePoll(predicate, pollInterval = undefined, maxTicks = Infinity) {
return new PromisePoll(predicate, pollInterval, maxTicks);
}
exports.promisePoll = promisePoll;
class PromisePoll {
constructor(callback, timeout, maxTicks) {
this.callback = callback;
this.timeout = timeout;
this.maxTicks = maxTicks;
this.resolve = fp_identity_js_1.fpIdentity;
this.id = null;
this.tickCount = 0;
this.promise = new Promise((resolve) => {
this.resolve = resolve;
this.id = setInterval(() => {
if (this.tickCount++ >= this.maxTicks) {
this.cancel(EResolutionState.TimedOut);
}
else if (this.callback()) {
this.cancel(EResolutionState.Resolved);
}
}, this.timeout);
});
}
getPromise() {
return this.promise;
}
cancel(reason = EResolutionState.Cancelled) {
if (this.id != null) {
clearInterval(this.id);
this.id = null;
this.resolve(reason);
}
}
}
//# sourceMappingURL=promise-poll.js.map