import msleep from './msleep'; interface UntilOptions { check?: (result: T) => boolean | Promise; timeout?: number; delay?: number; message?: string; attempts?: number; } export class TimeoutError extends Error { constructor(message: string, public readonly options?: Pick, 'timeout' | 'delay'>) { super(message); } } /** * Retry a function until a certain timeout. * @param {() => (Promise | T)} fn The function to test. * @param {UntilOptions} options The until options, {@see UntilOptions}. * @returns {Promise} */ export default function until(fn: () => T | Promise, options?: UntilOptions): Promise { const theTimeout = options?.timeout ?? 5000; let attempts = options?.attempts ?? 1; const { check, timeout, delay, message }: Required, 'attempts'>> = { check: (result) => !!result, timeout: theTimeout, delay: 0, message: `Timeout exceeded after waiting for ${theTimeout} ms`, ...options, }; return new Promise((resolve, reject) => { void (async () => { const stop = setTimeout(() => { clearTimeout(stop); reject(new TimeoutError(message, { timeout, delay })); }, timeout ?? 5000); let result: T; let pass: boolean; do { try { // Attempt to execute the callback result = await fn(); } catch (e) { // If the call back throws, check if it is retry-able (attempts >1) pass = false; attempts--; if (attempts === 0) { // Attempts exhausted, re-throw throw e; } continue; } // Validate the callback result pass = await check(result); // Wait some ms if necessary if (!pass && delay > 0) { await msleep(delay); } } while (!pass); resolve(result!); })(); }); }