Using Typescript promise instead of jQuery deferred

216 Views Asked by At

I am having the below lines of code which is using JQueryDeferred object from the type definition class jquery.d.ts. Trying to replace jQuery deferred to typescript promise.

Existing JQueryDeferred code;

class A {
   private b: class B = new B();

   public  function1(param:string):JQueryDeferred<object> {       
     var obj: JQueryDeferred<object> = $.Deferred();       
     b.registerFunction1(obj);       
     if(param) {//some other condition checking code)           
       obj.resolve();       
     }       
     return obj;    
   }
}

class B {

 public registerFunction1(obj:JQueryDeferred<object>): void {    
  domhandler.addEventListner(dom, 'onFunction1', onFunction1.bind(obj)); 
 }

 public onFunction1(obj:JQueryDeferred<object>, evt:KeyboardEvent):void {      
   obj.resolve(evt); 
 }

}

So far, I have refactored the lines of code for class A with;

class A {

   private b: class B = new B();

   public function1(param:string):Promise<object>{
     var obj: Promise<object> = new Promise((resolve, reject) => {
       b.registerFunction1(obj);
       if(param){//some other condition checking code
          resolve();
       }
      });
     return obj;
   }
}

But I am not sure how to rewrite the entire lines for class B, as I haven't seen promise objects passed as function arguments. Even though its passed, we cannot call resolve() of that promise object in the binder function "onFunction1" because it is not supported in typescript.

Can somebody help me to refactor the class B code lines to incorporate the typescript promise?

1

There are 1 best solutions below

0
trincot On

The idea is that you pass on the resolve function where you would previously pass on the deferred object. Something like this:

class A {
    private b: class B = new B();

    public function1(param:string):Promise<object>{
        return Promise<object> = new Promise((resolve, reject) => {
            b.registerFunction1(resolve);
            if (param) { //some other condition checking code
                resolve();
            }
        });
    }
}

class B {
    public registerFunction1(resolve): void {    
        domhandler.addEventListener(dom, 'onFunction1', resolve); 
    }
}

Unrelated, but be aware that a promise can only resolve once, while an event listener might call its callback multiple times. Moreover, if the param condition is true, the promise will resolve immediately, and calling resolve in the event listener will have no effect. These considerations are equally true in the version that uses a deferred object.