All files / src/common time.ts

88% Statements 22/25
100% Branches 3/3
66.66% Functions 6/9
100% Lines 14/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 36 37 38 39 40 41 42 43          3x             6x 6x       6x 4x 2x   2x             6x       3x 6x   3x   3x   3x   3x  
type TimeoutCallback<T> = (
  resolve: (value: T | PromiseLike<T>) => void,
  reject: (reason?: unknown) => void
) => void;
 
export const timeout = async <T>(
  prom: Promise<T>,
  timeoutMS: number,
  customErrorMessage?: string,
  timeoutCallback?: TimeoutCallback<T>
): Promise<T> => {
  let timer: NodeJS.Timeout | undefined;
  try {
    return await Promise.race<T>([
      prom,
      new Promise(
        (resolve, reject) =>
          (timer = setTimeout(() => {
            if (timeoutCallback) {
              return timeoutCallback(resolve, reject);
            }
            reject(
              new Error(customErrorMessage ?? `Timeout error ${timeoutMS} [MS]`)
            );
          }, timeoutMS))
      ),
    ]);
  } finally {
    clearTimeout(timer);
  }
};
 
export const sleep = (ms: number) =>
  new Promise((resolve, _rejects) => setTimeout(resolve, ms));
 
export const msToMin = (ms: number) => ms / 60_000;
 
export const minToMs = (min: number) => min * 60_000;
 
export const hourToMs = (hours: number) => hours * 3_600_000;
 
export const msToHours = (ms: number) => ms / 3_600_000;