@nesvet/n
Version:
Various utilities
37 lines • 1.11 kB
JavaScript
export function when(check, callback, options = {}) {
if (typeof callback == "object") {
options = callback;
callback = undefined;
}
const { interval = 1, timeout = null, context } = options;
let checkResolve;
let checkInterval;
let rejectionTimeout;
async function checkFunc() {
const result = await check();
if (result) {
checkResolve(result);
return true;
}
return false;
}
return new Promise((resolve, reject) => {
checkResolve = resolve;
checkFunc().then(isPassed => {
if (!isPassed) {
checkInterval = setInterval(checkFunc, interval);
if (timeout)
rejectionTimeout = setTimeout(reject, timeout);
}
});
}).then(result => {
clearInterval(checkInterval);
clearTimeout(rejectionTimeout);
callback?.call(context, result);
return result;
}, () => {
clearInterval(checkInterval);
throw new Error("timeout");
});
}
//# sourceMappingURL=when.js.map