All files waitUntilDefined.ts

86.67% Statements 13/15
50% Branches 1/2
100% Functions 2/2
85.71% Lines 12/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 368x                           8x       1x 1x   43x 43x     43x 1x 42x 42x   1x 1x        
import { delay } from './delay';
 
/**
 * Function repeats provided call until it returns not null or undefined value.
 * If this process exceeds `maxDurationMs` function will throw
 * of those function calls.
 *
 * @param fn - The function to invoke.
 * @param maxDurationMs - Max waiting duration
 * @example
 * const result = await waitUntilDefined(() => document.body.getElementById("#app"))
 * @category Utility
 * @throws If if fn does not return not nil value in given time frame
 */
export async function waitUntilDefined<T>(
  fn: () => T | undefined,
  maxDurationMs: number
): Promise<NonNullable<T>> {
  const start = Date.now();
  return new Promise<NonNullable<T>>(async resolve => {
    while (true) {
      const diff = Date.now() - start;
      Iif (diff > maxDurationMs) {
        throw new Error(`Timeout after ${maxDurationMs}`);
      }
      const v = fn();
      if (v == null) {
        await delay(1);
        continue;
      }
      resolve(v as NonNullable<T>);
      return;
    }
  });
}