Embracing Typescript promises over jQuery deferred for improved code efficiency and reliability

Currently, I have the following lines of code that utilize the JQueryDeferred object from the type definition class jquery.d.ts. My goal is to replace jQuery deferred with TypeScript promises.

Here is the 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 code for class A as follows:

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;
   }
}

However, I am unsure how to rewrite the complete code for class B, as I have not encountered promise objects being passed as function arguments before. Even if they were passed, calling resolve() of that promise object in the binder function "onFunction1" is not supported in TypeScript.

Could someone assist me in refactoring the code lines for class B to integrate TypeScript promises?

Answer №1

The concept here is to replace passing the deferred object with the resolve function. This enables you to achieve something along these lines:

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

    public performAction(param:string):Promise<object>{
        return Promise((resolve, reject) => {
            b.registerCallback(resolve);
            if (param) { //additional condition checks
                resolve();
            }
        });
    }
}

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

It's worth noting that a promise can only resolve once, unlike an event listener which can trigger its callback multiple times. Additionally, if the specified condition in param is met, the promise will resolve immediately, rendering the call to resolve within the event listener ineffective. These factors hold true for both approaches using either the resolve function or a deferred object.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Resetting a JQuery button to its initial state

I have a button that, when clicked, rotates to 25deg thanks to Jquery. Now, I want it so that if I click the button again, it returns to its original position. Here is what I have tried: $(document).ready(function() { $(function() { ...

Mapping a bar chart on a global scale

Are there any methods available to create bar charts on a world map? The world map could be depicted in a 3D view resembling a Globe or in a 2D format. It should also have the capability to zoom in at street level. Does anyone have suggestions or examples ...

Manipulate table rows in real-time using jQuery to effortlessly add or remove rows

UPDATE: After setting a goal to delete rows, I am now facing an issue with recreating a deletion button in the row previous to the one that was just deleted. Here is the code snippet: HTML: <div id="container"> <img id="header" src="images/ ...

What could be causing my form to malfunction when attempting to submit data using Ajax and an external PHP script that is handling two string inputs?

Hello, I am facing an issue while trying to utilize Ajax to interact with a PHP file and submit both inputs (fullname and phonenumber). When I click the submit button, it simply refreshes the page without performing the desired action. Below is the code I ...

Is it possible to compile using Angular sources while in Ivy's partial compilation mode?

Error: NG3001 Unsupported private class ObjectsComponent. The class is visible to consumers via MasterLibraryLibModule -> ObjectsComponent, but is not exported from the top-level library entrypoint. 11 export class ObjectsComponent implements OnInit { ...

Automating the indexing of scroll positions in JavaScript

My code is functioning properly, but I had to input each case manually. Now, I am working on optimizing it to make it adaptable for any situation. However, I am struggling to figure out the best approach. The main objective is to determine my position on ...

Can anyone provide guidance on incorporating jQuery typing into an angular2 seed project?

I'm struggling to incorporate jQuery typings into my Angular2-seed project. Within my component, I am utilizing jQuery in the following manner: declare let $: any; export class LeafletComponent implements OnInit { ngOnInit(): void { th ...

Issues with Jquery Ajax implementation causing data not to display in HTML

Hey team! I've got an ajax function set up (see code below) that sends data to a php file, retrieves it, and posts it in an html div. I have two different pages within the same folder using this code - one is 'loggedout' and the other is &a ...

Concealing scroll bars while still maintaining the ability to scroll by using overflow:scroll

Similar Question: How to hide the scrollbar while still allowing scrolling with mouse and keyboard I have created a sidebar for a web application that needs to enable users to scroll through it without displaying a scrollbar. The content is 500px high ...

Node.js does not support jQuery Ajax for making HTTPS GET or POST requests

var app, express, fs, jquery, jsdom; jsdom = require('jsdom'); fs = require('fs'); express = require('express'); jquery = fs.readFileSync('./jquery-2.0.3.min.js').toString(); jsdom.env({ ...

Enhance the Error class in Typescript

I have been attempting to create a custom error using my "CustomError" class to be displayed in the console instead of the generic "Error", without any success: class CustomError extends Error { constructor(message: string) { super(`Lorem "${me ...

Creating a generic hashmap that can accept dynamic keys and an array of type T

In my attempt to create a robust typing interface for a hashmap in typescript, The hashmap consists of a key with a dynamic string name, and a values array containing a Generic type. I attempted to define the interface as follows: export interfa ...

Oops! The 'map' property cannot be found in the type 'Observable<User>'

In my online shopping project that combines Angular and Firebase, I implemented the AuthGuard to verify user login status before accessing various links including ./check-out. However, I encountered an issue with importing map for Observable.User. All comp ...

Click to enlarge font size across the entire project

I'm working on a project for elderly users and my client wants a feature where they can easily adjust the font size throughout the application with just one click of a button. What is the best approach for implementing this functionality? My initial ...

scrolling through a list using .slice choosing an excessive amount of items

Is it possible to create a dynamic pager that can be customized using parameters from the URL? I have noticed that when I hardcode the perTime variable, everything works fine. However, as soon as I try to use a parameter from the URL, the page starts behav ...

Issue: An error occurred while trying to parse JSON data in TypeScript due to an undefined 'description' property

Encountering an error message when attempting to retrieve the description attribute from the following Sample Json. Error: TypeError: Cannot read property 'description' of undefined when trying to access json data in typescript import {Age ...

Exploring the world of jQuery animation and background colors with Animate()

I'm currently attempting to implement a basic pulse effect by utilizing JQuery to modify the background color. However, I am facing issues with animating the backgroundColor property. function show_user(dnid) { /* dnid represents the HTML ID of a ...

Analyzing the number of rows by utilizing variables stored in an array

Greetings everyone! I am currently attempting to compare the number of rows returned by two queries, for which the values are fetched from an array within a while loop. Below is the PHP code snippet: $get_section = "SELECT * FROM s ...

Navigating Angular: Uncover the Secrets of Unwrapping Json Data

I need some help with parsing Json data in Angular TypeScript. The data is structured as follows: https://i.sstatic.net/H7s8q.png When calling a REST API, I want to convert a Java class object into an array of model classes. How can this be achieved? "g ...

reveal or conceal content on hover of mouse pointer

I am currently working on a section that functions like jQuery tabs, but instead of requiring a click to activate, I want it to work on mouse hover. The current implementation is somewhat buggy - when hovering over a specific section, it displays as expe ...