promise.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132
  1. /**
  2. * Wait for {@link ms} milliseconds
  3. *
  4. * This function is a promisified `setTimeout`. It returns a promise that
  5. * resolves after {@link ms} milliseconds.
  6. */
  7. export const wait = (ms: number) =>
  8. new Promise((resolve) => setTimeout(resolve, ms));
  9. /**
  10. * Await the given {@link promise} for {@link timeoutMS} milliseconds. If it
  11. * does not resolve within {@link timeoutMS}, then reject with a timeout error.
  12. *
  13. * Note that this does not abort {@link promise} itself - it will still get
  14. * resolved to completion, just its result will be ignored if it gets resolved
  15. * after we've already timed out.
  16. */
  17. export const withTimeout = async <T>(promise: Promise<T>, ms: number) => {
  18. let timeoutId: ReturnType<typeof setTimeout>;
  19. const rejectOnTimeout = new Promise<T>((_, reject) => {
  20. timeoutId = setTimeout(
  21. () => reject(new Error("Operation timed out")),
  22. ms,
  23. );
  24. });
  25. const promiseAndCancelTimeout = async () => {
  26. const result = await promise;
  27. clearTimeout(timeoutId);
  28. return result;
  29. };
  30. return Promise.race([promiseAndCancelTimeout(), rejectOnTimeout]);
  31. };