index.ts 675 B

1234567891011121314151617181920212223
  1. import { CustomError } from "../error";
  2. export const promiseWithTimeout = async <T>(
  3. request: Promise<T>,
  4. timeout: number,
  5. ): Promise<T> => {
  6. const timeoutRef = { current: null };
  7. const rejectOnTimeout = new Promise<null>((_, reject) => {
  8. timeoutRef.current = setTimeout(
  9. () => reject(Error(CustomError.WAIT_TIME_EXCEEDED)),
  10. timeout,
  11. );
  12. });
  13. const requestWithTimeOutCancellation = async () => {
  14. const resp = await request;
  15. clearTimeout(timeoutRef.current);
  16. return resp;
  17. };
  18. return await Promise.race([
  19. requestWithTimeOutCancellation(),
  20. rejectOnTimeout,
  21. ]);
  22. };