timed.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  2. /** @author Brian Cavalier */
  3. /** @author John Hann */
  4. (function(define) { 'use strict';
  5. define(function(require) {
  6. var env = require('../env');
  7. var TimeoutError = require('../TimeoutError');
  8. function setTimeout(f, ms, x, y) {
  9. return env.setTimer(function() {
  10. f(x, y, ms);
  11. }, ms);
  12. }
  13. return function timed(Promise) {
  14. /**
  15. * Return a new promise whose fulfillment value is revealed only
  16. * after ms milliseconds
  17. * @param {number} ms milliseconds
  18. * @returns {Promise}
  19. */
  20. Promise.prototype.delay = function(ms) {
  21. var p = this._beget();
  22. this._handler.fold(handleDelay, ms, void 0, p._handler);
  23. return p;
  24. };
  25. function handleDelay(ms, x, h) {
  26. setTimeout(resolveDelay, ms, x, h);
  27. }
  28. function resolveDelay(x, h) {
  29. h.resolve(x);
  30. }
  31. /**
  32. * Return a new promise that rejects after ms milliseconds unless
  33. * this promise fulfills earlier, in which case the returned promise
  34. * fulfills with the same value.
  35. * @param {number} ms milliseconds
  36. * @param {Error|*=} reason optional rejection reason to use, defaults
  37. * to a TimeoutError if not provided
  38. * @returns {Promise}
  39. */
  40. Promise.prototype.timeout = function(ms, reason) {
  41. var p = this._beget();
  42. var h = p._handler;
  43. var t = setTimeout(onTimeout, ms, reason, p._handler);
  44. this._handler.visit(h,
  45. function onFulfill(x) {
  46. env.clearTimer(t);
  47. this.resolve(x); // this = h
  48. },
  49. function onReject(x) {
  50. env.clearTimer(t);
  51. this.reject(x); // this = h
  52. },
  53. h.notify);
  54. return p;
  55. };
  56. function onTimeout(reason, h, ms) {
  57. var e = typeof reason === 'undefined'
  58. ? new TimeoutError('timed out after ' + ms + 'ms')
  59. : reason;
  60. h.reject(e);
  61. }
  62. return Promise;
  63. };
  64. });
  65. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));