You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 816B

123456789101112131415161718192021222324252627282930313233343536
  1. 'use strict';
  2. const pFinally = require('p-finally');
  3. class TimeoutError extends Error {
  4. constructor(message) {
  5. super(message);
  6. this.name = 'TimeoutError';
  7. }
  8. }
  9. module.exports = (promise, ms, fallback) => new Promise((resolve, reject) => {
  10. if (typeof ms !== 'number' || ms < 0) {
  11. throw new TypeError('Expected `ms` to be a positive number');
  12. }
  13. const timer = setTimeout(() => {
  14. if (typeof fallback === 'function') {
  15. resolve(fallback());
  16. return;
  17. }
  18. const message = typeof fallback === 'string' ? fallback : `Promise timed out after ${ms} milliseconds`;
  19. const err = fallback instanceof Error ? fallback : new TimeoutError(message);
  20. reject(err);
  21. }, ms);
  22. pFinally(
  23. promise.then(resolve, reject),
  24. () => {
  25. clearTimeout(timer);
  26. }
  27. );
  28. });
  29. module.exports.TimeoutError = TimeoutError;