All files timeout.ts

84.61% Statements 11/13
100% Branches 2/2
80% Functions 4/5
81.81% Lines 9/11

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  1x 1x                               4x 4x 4x 4x 3x 3x           1x      
import type {Code} from './types';
 
/**
 * Waits for given number of milliseconds before timing out. If provided code
 * block does not complete within the given time, the promise will be rejected
 * with `new Error('TIMEOUT')` error.
 *
 * ```ts
 * const result = await timeout(1000, async () => {
 *   return 123;
 * });
 * ```
 *
 * @param ms Number of milliseconds to wait before timing out.
 * @param code Code block or promise to execute.
 * @returns The result of the code block or promise.
 */
export const timeout = <T>(ms: number, code: Code<T> | Promise<T>): Promise<T> =>
  new Promise<T>((resolve, reject) => {
    const timer: any = setTimeout(() => reject(new Error('TIMEOUT')), ms);
    const promise = typeof code === 'function' ? code() : code;
    promise.then(
      (result) => {
        clearTimeout(timer);
        resolve(result);
      },
      (error) => {
        clearTimeout(timer);
        reject(error);
      },
    );
  });