Timeout a Promise

Wraps a promise with a timeout to reject if it takes too long.

TypeScript
david

13 weeks ago

function timeoutPromise<T>(promise: Promise<T>, ms: number): Promise<T> {
  const timeout = new Promise<never>((_, reject) =>
    setTimeout(() => reject(new Error("Timeout exceeded")), ms)
  );
  return Promise.race([promise, timeout]);
}
0