index.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // Copyright (c) 2015-2017 David M. Lee, II
  2. 'use strict';
  3. /**
  4. * Local reference to TimeoutError
  5. * @private
  6. */
  7. var TimeoutError;
  8. /**
  9. * Rejects a promise with a {@link TimeoutError} if it does not settle within
  10. * the specified timeout.
  11. *
  12. * @param {Promise} promise The promise.
  13. * @param {number} timeoutMillis Number of milliseconds to wait on settling.
  14. * @returns {Promise} Either resolves/rejects with `promise`, or rejects with
  15. * `TimeoutError`, whichever settles first.
  16. */
  17. var timeout = module.exports.timeout = function(promise, timeoutMillis) {
  18. var error = new TimeoutError(),
  19. timeout;
  20. return Promise.race([
  21. promise,
  22. new Promise(function(resolve, reject) {
  23. timeout = setTimeout(function() {
  24. reject(error);
  25. }, timeoutMillis);
  26. }),
  27. ]).then(function(v) {
  28. clearTimeout(timeout);
  29. return v;
  30. }, function(err) {
  31. clearTimeout(timeout);
  32. throw err;
  33. });
  34. };
  35. /**
  36. * Exception indicating that the timeout expired.
  37. */
  38. TimeoutError = module.exports.TimeoutError = function() {
  39. Error.call(this)
  40. this.stack = Error().stack
  41. this.message = 'Timeout';
  42. };
  43. TimeoutError.prototype = Object.create(Error.prototype);
  44. TimeoutError.prototype.name = "TimeoutError";