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?
The idea is that you pass on the
resolvefunction where you would previously pass on the deferred object. Something like this:Unrelated, but be aware that a promise can only resolve once, while an event listener might call its callback multiple times. Moreover, if the
paramcondition is true, the promise will resolve immediately, and callingresolvein the event listener will have no effect. These considerations are equally true in the version that uses a deferred object.