about summary refs log tree commit diff
path: root/src/lib/async/bundle.ts
blob: e307cd4373ae21e1b3ec348a80ae78c44d3f417f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
type BundledFn<Args extends readonly unknown[], Res> = (
  ...args: Args
) => Promise<Res>

/**
 * A helper which ensures that multiple calls to an async function
 * only produces one in-flight request at a time.
 */
export function bundleAsync<Args extends readonly unknown[], Res>(
  fn: BundledFn<Args, Res>,
): BundledFn<Args, Res> {
  let promise: Promise<Res> | undefined
  return async (...args) => {
    if (promise) {
      return promise
    }
    promise = fn(...args)
    try {
      return await promise
    } finally {
      promise = undefined
    }
  }
}