export function debouncePromise<T extends (...args: any[]) => Promise<any>>(factory: T, delayMs: number): T {
  let currentArgs: any[]
  let timeout = 0
  let resolvers: ((value: any) => void)[] = []
  return ((...args: any[]) => {
    clearTimeout(timeout)
    currentArgs = args
    const promise = new Promise<any>(resolve => {
      resolvers.push(resolve)
    })
    timeout = window.setTimeout(async () => {
      const res = resolvers
      resolvers = []
      const result = await factory(...currentArgs)
      res.forEach(r => r(result))
    }, delayMs)
    return promise
  }) as T
}
