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.

Deferred.js 1.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. /**
  2. * Promise-like object which can be passed around for resolving it later. It
  3. * implements the "thenable" interface, so it can be used wherever a Promise
  4. * could be used.
  5. *
  6. * In addition a "reject on timeout" functionality is provided.
  7. */
  8. export default class Deferred {
  9. /**
  10. * Instantiates a Deferred object.
  11. */
  12. constructor() {
  13. this.promise = new Promise((resolve, reject) => {
  14. this.resolve = (...args) => {
  15. this.clearRejectTimeout();
  16. resolve(...args);
  17. };
  18. this.reject = (...args) => {
  19. this.clearRejectTimeout();
  20. reject(...args);
  21. };
  22. });
  23. this.then = this.promise.then.bind(this.promise);
  24. this.catch = this.promise.catch.bind(this.promise);
  25. }
  26. /**
  27. * Clears the reject timeout.
  28. */
  29. clearRejectTimeout() {
  30. clearTimeout(this._timeout);
  31. }
  32. /**
  33. * Rejects the promise after the given timeout.
  34. */
  35. setRejectTimeout(ms) {
  36. this._timeout = setTimeout(() => {
  37. this.reject(new Error('timeout'));
  38. }, ms);
  39. }
  40. }