Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

Deferred.ts 1.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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<T = any> {
  9. private _timeout?: Timeout;
  10. promise: Promise<T>;
  11. resolve: (value: T | PromiseLike<T>) => void;
  12. reject: (reason?: any) => void;
  13. then: Promise<T>['then'];
  14. catch: Promise<T>['catch'];
  15. /**
  16. * Instantiates a Deferred object.
  17. */
  18. constructor() {
  19. this.promise = new Promise<T>((resolve, reject) => {
  20. this.resolve = (value: T | PromiseLike<T>) => {
  21. this.clearRejectTimeout();
  22. resolve(value);
  23. };
  24. this.reject = (reason?: any) => {
  25. this.clearRejectTimeout();
  26. reject(reason);
  27. };
  28. });
  29. this.then = this.promise.then.bind(this.promise);
  30. this.catch = this.promise.catch.bind(this.promise);
  31. }
  32. /**
  33. * Clears the reject timeout.
  34. */
  35. clearRejectTimeout(): void {
  36. clearTimeout(this._timeout);
  37. }
  38. /**
  39. * Rejects the promise after the given timeout.
  40. */
  41. setRejectTimeout(ms: number): void {
  42. this._timeout = setTimeout(() => {
  43. this.reject(new Error('timeout'));
  44. }, ms);
  45. }
  46. }