All files / utils onceMeanwhile.ts

100% Statements 11/11
75% Branches 3/4
100% Functions 3/3
100% Lines 11/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                        1x   1x 5x 2x 2x 2x 2x 2x 2x       5x   1x    
import { AnyAsyncFunction } from '../types'
import { isPromiseLike } from './isPromiseLike'
 
/**
 * 同一时间对函数的调用只会触发一次运行。
 *
 * @param fn 函数
 * @returns 返回函数调用结果
 */
export function onceMeanwhile<TFunc extends AnyAsyncFunction>(
  fn: TFunc,
): TFunc {
  let running = false
  let result: Promise<any>
  const proxy = (...args: any[]) => {
    if (!running) {
      running = true
      const res = fn(...args)
      if (isPromiseLike(res)) {
        result = res.then(_ => {
          running = false
          return _
        })
      }
    }
    return result
  }
  return proxy as any
}