Asynchronous jQuery operations using promises and finally functionality

I am attempting to interact with a REST api using jQuery's ajax feature.

My goal is to return the Promise<Customer> object, but I am encountering an error stating that the property finally is missing. It used to work before, so I assume there have been some recent changes. However, I am struggling to figure out how to include the missing finally property.

I believe there must be a simple solution, but unfortunately, I haven't been able to find a fix online.

The issue is within the following class:

export class ServiceCustomer {
    public requestCustomers(): Promise<Customer> {
        const dataString: ResourceParamCustomer = {
            something: 'some entry',
            nextthing: 'other entry',
        };

        return $.ajax({
            contentType: 'application/json',
            data: JSON.stringify(dataString),
            dataType: 'json',
            type: 'POST',
            url: 'http://localhost:3000/api/customer/list',
        });
    }
}

The error message received:

ERROR in [at-loader] ./src/Service/ServiceCustomer.ts:12:15 
    TS2741: Property 'finally' is missing in type 'jqXHR<any>' but required in type 'Promise<Customer>'.

Key information from the package.json:

{
    ...
    "dependencies": {
        ...
        "@types/jquery": "3.3.31",
        ...
        "jquery": "3.4.1",
        "popper.js": "1.16.0",
        ...
    },
    "devDependencies": {
        "autoprefixer": "9.7.1",
        "awesome-typescript-loader": "5.2.1",
        "clean-webpack-plugin": "3.0.0",
        ...
        "html-webpack-plugin": "3.2.0",
        ...
        "tslint": "5.20.1",
        "typescript": "3.7.2",
        "typings-for-css-modules-loader": "1.7.0",
        ...
    },
    ...
}

The tsconfig.json configuration:

{
    "compilerOptions": {
        "outDir": "./dist/",
        "sourceMap": true,
        "noImplicitAny": true,
        "module": "commonjs",
        "target": "es2015",
        "jsx": "react",
    },
    "include": [
        "./src/**/*"
    ]
}

Answer №1

The jQuery library's promise feature does not include a finally method, making it incompatible with TypeScript's Promise definition.

While the jQuery promise aligns with TypeScript's PromiseLike definition due to its then callback implementation, it differs in functionality as it supports multiple parameters for callbacks as described in the jQuery ajax documentation.

jqXHR.then(
    function( data, textStatus, jqXHR ) {},
    function( jqXHR, textStatus, errorThrown ) {}
);

To convert the jQuery promise into a native Promise object, you can create an instance of a Promise as shown below.

export class ServiceCustomer {
    public requestCustomers(): Promise<Customer> {
        const dataString: ResourceParamCustomer = {
            something: 'some entry',
            nextthing: 'other entry',
        };

        return new Promise<Customer>((resolve, reject) => {
            $.ajax<Customer>({
                contentType: 'application/json',
                data: JSON.stringify(dataString),
                dataType: 'json',
                type: 'POST',
                url: 'http://localhost:3000/api/customer/list',
            }).then(
                (data, textStatus, jqXHR) => {
                    resolve(data);
                },
                (jqXHR, textStatus, errorThrown) => {
                    const error = createError(jqXHR, textStatus, errorThrown);
                    reject(error);
                }
            );
        });
    }
}

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

Creating a URL using Form Fields with Javascript or jQuery - Reg

Creating a Custom URL with Form Fields using JavaScript or jQuery I am looking to generate an external link by incorporating a form with a dynamic variable as shown below: (Where 2500 can be customized based on user input) The final URL will be display ...

Creating IPv6 Mask from IPv6 Prefix Using Javascript: A Step-by-Step Guide

Write a JavaScript/TypeScript function that can convert IPv6 prefixes (ranging from 0 to 128) into the corresponding mask format (using the ffff:ffff style). Here are some examples: 33 => 'ffff:ffff:8000:0000:0000:0000:0000:0000' 128 => ...

Why is it that my upvote button seems to only function properly for the initial post?

Following the guidelines from tangowithdjango, I implemented a 'like' button in my forum app. The HTML file and Javascript: <script> $(document).ready(function(){ $("#upvote").click(function(){ var postid; postid = $(this).att ...

Submitting a POST request from a Typescript Angular 2 application to a C# MVC backend

Having trouble passing a payload using Typescript service in an http.post request Here is my TypeScript code: saveEdits(body: Object): Observable<Animal[]> { let bodyString = JSON.stringify(body); let headers = new Headers({ 'Content- ...

Ways to collect email address or name from an email message

Suppose I send an email to someone with a link at the bottom. The text of the link might be something like click me. When the user clicks on this link, they will be directed to a webpage. On this webpage, a message saying "Thank you" will be displayed a ...

Allow iframe to be edited within jsfiddle

I have a question that I need to ask soon, but first I need an editable iframe in jsfiddle. It's working fine on my local machine, but not on jsfiddle. I believe it's because of the frames being used? On my local machine, I use: setTimeout(&apo ...

Sliding multiple divs up and down with jQuery

Here is the code that I am working with: JavaScript: $(".Head").click(function () { if ($(".Body").is(":hidden")) { $(".Body").slideDown('fast'); } else { $(".Body").slideUp('fast'); } }); HTML: ...

Encountered an issue with the Dynamic Form: TypeError - The property 'value' is undefined and cannot be read

RESOLVED An incorrect value was causing an issue with the onChange function. public onChange = (e:any, key:any) => { this.setState({ [key]: e.target.value }); }; I'm struggling to resolve an error while inputting data into my form in T ...

Identifying the delete key input across the entire webpage using jQuery

I am trying to detect the delete key press anywhere on the page. Here is the code snippet I have been using: $(document).keydown(function (e) { console.log(e); }); However, I am facing issues with getting the event to fire at all. Any suggestions? ...

Tips for automatically choosing several choices from a multiple-select using Chosen.JS

I am struggling to programmatically select multiple values in a multiple select using chosenJS/chosen.js while still ensuring that the selected values are bound to my ng-model (angularJS). In this scenario, I have a list of users, some of whom are already ...

Tips for displaying the overlay in a jQuery UI modal dialog

The demonstration shows that the overlay is displayed correctly and all elements below it are disabled: <div class="ui-widget-overlay" style="width: 1920px; height: 650px; z-index: 1001;"></div> However, on my webpage, I am still able to inte ...

"Anticipate the presence of expression" mistake

On my page, users can choose a registration type and input content into the tinymce textarea to associate that content with the selected registration type. However, an error "expression expected" is appearing in the code below? The console indicates that ...

Discovering the generic parameter in the return type using TypeScript

I am struggling with a specific issue export type AppThunk<ReturnType> = ThunkAction< ReturnType, RootState, unknown, Action<string> >; After implementing the above code snippet export const loadCourse = (id: string): AppThunk ...

Include a Class into a label using jQuery

I am having an issue where I need to specifically add the error class to a <label> with the name attribute set to choice_16_0. However, when I try to achieve this using my code, it ends up changing all labels on the page to <label for="choice_16_0 ...

Defining TypeScript class events by extending EventEmitter

I have a class that extends EventEmitter and is capable of emitting the event hello. How can I properly declare the on method with a specific event name and listener signature? class MyClass extends events.EventEmitter { emitHello(name: string): void ...

Refresh SQL Query using AJAX/jQuery

I’m really confused on how to utilize AJAX to reload a specific section of a webpage that executes an SQL query via PHP on my database. Look at this code snippet: <tbody> <?php $stmt = $DB_con->prepare("SELECT * FROM script ...

Encountering NoResourceAdapterError when using @admin-bro/nestjs alongside @admin-bro/sequelize and MySQL?

Encountering a similar issue with '@admin-bro/sequelize' NoResourceAdapterError: No compatible adapters found for the provided resource import { Database, Resource } from '@admin-bro/sequelize'; import { AdminModule } from '@admin- ...

Rearranging items within an array in a React component

Currently, I am facing a situation where I have created a list that dynamically adds a React Node upon clicking a button. The final layout of the model looks like this: Here is the code snippet for your reference: import * as React from 'react' ...

Tips for generating a .csv document using data from an array?

I am currently utilizing a PHP class to validate email addresses in real-time. The PHP Script is functioning as expected: validating the emails and displaying the results on the same page by generating a <td> element for each validated email. Howeve ...

Retrieve the value of a cell in Google Sheets

Seeking assistance on how to retrieve the content of a cell in Google Sheets and store it for comparison purposes at a later time. My search efforts have led me to various online resources such as the Visualization API and the Sheets Script, but I have n ...