@bitty/insist
Version:
Insistently runs a callback and only resolves the promise when its result is truthy.
44 lines (42 loc) • 1.3 kB
JavaScript
/**
* Waits the received time in milliseconds.
* @param time - The delay time in milliseconds.
*/
function wait(time) {
return new Promise(function (resolve) { return setTimeout(resolve, time); });
}
/**
* Runs condition asynchronously. Assumes `false` if condition throws an error.
* @param condition - The condition function.
*/
function check(condition) {
try {
return Promise.resolve(condition()).catch(function () { return false; });
}
catch (_a) {
return Promise.resolve(false);
}
}
/**
* Insists on a condition until it is satisfied. When the condition is not
* satisfied there is a delay, defined in milliseconds, for it to be checked
* again.
* @example
* ```js
* insist(() => window.document.readyState === 'complete').then(() => {
* console.log('The DOM is ready!');
* });
* ```
* @param condition - The condition function.
* @param time - The delay time, in milliseconds, to execute condition again.
*/
function insist(condition, time) {
if (time === void 0) { time = 200; }
return check(condition).then(function (success) {
if (success)
return;
return wait(time).then(function () { return insist(condition, time); });
});
}
export { insist as default };
//# sourceMappingURL=insist.mjs.map