Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

1.1 KB
Raw Blame
export class ProbeTimeoutError extends Error {
  constructor() {
    super("Timed out");
    this.name = "ProbeTimeoutError";
  }
}

/**
 * Resolve with `work`, or reject with ProbeTimeoutError after `ms`. The
 * abandoned promise keeps running, so its later rejection is swallowed here
 * instead of surfacing as an unhandled rejection.
 */
export function withTimeout<T>(
  work: (signal: AbortSignal) => Promise<T>,
  ms: number,
): Promise<T> {
  const controller = new AbortController();
  let timer: ReturnType<typeof setTimeout> | undefined;
  // Drizzle queries are lazy thenables that run again on every `.then()`;
  // wrapping once makes the catch handler and the race share one execution.
  const pending = Promise.resolve(work(controller.signal));
  pending.catch(() => {});
  const timeout = new Promise<never>((_, reject) => {
    timer = setTimeout(() => {
      // Settle first: aborting can reject `work` synchronously, and that
      // abort error must not win the race over the timeout.
      reject(new ProbeTimeoutError());
      controller.abort();
    }, ms);
  });
  return Promise.race([pending, timeout]).finally(() => clearTimeout(timer));
}