timeout.js 964 B

123456789101112131415161718192021222324252627282930
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.timeout = void 0;
  4. /**
  5. * Waits for given number of milliseconds before timing out. If provided code
  6. * block does not complete within the given time, the promise will be rejected
  7. * with `new Error('TIMEOUT')` error.
  8. *
  9. * ```ts
  10. * const result = await timeout(1000, async () => {
  11. * return 123;
  12. * });
  13. * ```
  14. *
  15. * @param ms Number of milliseconds to wait before timing out.
  16. * @param code Code block or promise to execute.
  17. * @returns The result of the code block or promise.
  18. */
  19. const timeout = (ms, code) => new Promise((resolve, reject) => {
  20. const timer = setTimeout(() => reject(new Error('TIMEOUT')), ms);
  21. const promise = typeof code === 'function' ? code() : code;
  22. promise.then((result) => {
  23. clearTimeout(timer);
  24. resolve(result);
  25. }, (error) => {
  26. clearTimeout(timer);
  27. reject(error);
  28. });
  29. });
  30. exports.timeout = timeout;