UNPKG

@bitty/insist

Version:

Insistently runs a callback and only resolves the promise when its result is truthy.

52 lines (48 loc) 1.8 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.insist = factory()); })(this, (function () { 'use strict'; /** * 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); }); }); } return insist; })); //# sourceMappingURL=insist.umd.js.map