All files codeMutex.ts

100% Statements 10/10
100% Branches 2/2
100% Functions 2/2
100% Lines 10/10

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  2x 2x         2x   13x 57x 32x 25x 25x     25x  
import type {Code} from './types';
 
/**
 * Executes only one instance of give code at a time. If other calls come in in
 * parallel, they get resolved to the result of the ongoing execution.
 */
export const codeMutex = <T>() => {
  let result: Promise<T> | undefined;
  return async (code: Code<T>): Promise<T> => {
    if (result) return result;
    try {
      return await (result = code());
    } finally {
      result = undefined;
    }
  };
};