Deferred.js 822 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. "use strict";
  2. const { TimeoutError } = require("./TimeoutError");
  3. class Deferred {
  4. constructor() {
  5. this._timeout = null;
  6. this._promise = new Promise((resolve, reject) => {
  7. this._reject = reject;
  8. this._resolve = resolve;
  9. });
  10. }
  11. registerTimeout(timeoutInMillis, callback) {
  12. if (this._timeout) return;
  13. this._timeout = setTimeout(() => {
  14. callback();
  15. this.reject(new TimeoutError("Operation timeout"));
  16. }, timeoutInMillis);
  17. }
  18. _clearTimeout() {
  19. if (!this._timeout) return;
  20. clearTimeout(this._timeout);
  21. this._timeout = null;
  22. }
  23. resolve(value) {
  24. this._clearTimeout();
  25. this._resolve(value);
  26. }
  27. reject(error) {
  28. this._clearTimeout();
  29. this._reject(error);
  30. }
  31. promise() {
  32. return this._promise;
  33. }
  34. }
  35. module.exports = Deferred;