All files / src/func defer.ts

71.42% Statements 10/14
50% Branches 1/2
50% Functions 4/8
71.42% Lines 10/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77                                                                                      34x 34x 34x   34x   34x 1x 1x     34x                         34x         34x        
//https://gist.github.com/uxder/b9bd3811e0508fae42c1df64155b9c8b
 
/**
 * A basic deferred promise.  Allows you to resolve/reject a promise at a later
 * time.
 *
 *
 * ```ts
 *
 * let defer = new Defer();
 *
 * // Resolve the defer at a later time.
 * let hello = ()=> {
 *   defer.resolve({ message : 'you said hello'});
 *
 *   // If you need to reject.
 *   // defer.reject();
 * }
 *
 *
 * // Get the promise and handle it.
 * defer.getPromise().then((data)=> {
 *   console.log(data.message); // you said hello
 * })
 *
 * window.setTimeout(()=> {
 *   hello();
 * }, 200)
 *
 *
 *
 * ```
 *
 * @tested
 */
export class Defer {
  public resolve: Function;
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  public promise: Promise<any>;
  public reject: Function;
  public complete: boolean;
 
  constructor() {
    this.resolve = () => {};
    this.reject = () => {};
    this.complete = false;
 
    this.promise = new Promise((resolve: Function, reject: Function) => {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      this.resolve = (data: any) => {
        this.complete = true;
        return resolve(data);
      };
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      this.reject = (data: any) => {
        this.complete = true;
        return reject(data);
      };
    });
  }
 
  /**
   * Returns the deferred promise.  If the defer was already completed for
   * some reason, will return a promise that is immediately resolved.
   */
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  getPromise(): Promise<any> {
    Iif (this.complete) {
      return new Promise((resolve: Function) => {
        resolve();
      });
    } else {
      return this.promise;
    }
  }
}