timeout.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. "use strict";
  2. var customError = require("es5-ext/error/custom")
  3. , isValue = require("es5-ext/object/is-value")
  4. , ensurePromise = require("es5-ext/object/ensure-promise")
  5. , nextTick = require("next-tick")
  6. , ensureTimeout = require("../valid-timeout");
  7. module.exports = function (/* timeout */) {
  8. ensurePromise(this);
  9. var timeout = arguments[0];
  10. if (isValue(timeout)) timeout = ensureTimeout(timeout);
  11. return new this.constructor(
  12. function (resolve, reject) {
  13. var isSettled = false, timeoutId;
  14. var timeoutCallback = function () {
  15. if (isSettled) return;
  16. reject(
  17. customError(
  18. "Operation timeout (exceeded " +
  19. (isValue(timeout) ? timeout + "ms" : "tick") +
  20. ")",
  21. "PROMISE_TIMEOUT"
  22. )
  23. );
  24. };
  25. if (isValue(timeout)) timeoutId = setTimeout(timeoutCallback, timeout);
  26. else nextTick(timeoutCallback);
  27. this.then(
  28. function (value) {
  29. isSettled = true;
  30. clearTimeout(timeoutId);
  31. resolve(value);
  32. },
  33. function (reason) {
  34. isSettled = true;
  35. clearTimeout(timeoutId);
  36. reject(reason);
  37. }
  38. );
  39. }.bind(this)
  40. );
  41. };