1
votes

a simple function in typescript:

callAPI ():JSONObject{
    let j:JSONObject;
    $.ajax().done((data, textStatus, jqXHR)=>{
        //some operation around data
        j = data;
        return j;
    });
}

The error is very straight forward,

A function whose declared type is neither 'void' nor 'any' must return a value.

I just don't know how to fix since i can't return that object when the ajax is not finish. Who knows how to deal with this situation?

1
There is a reason $.ajax() doesn't return an HTTP response: it can't, since an AJAX request is, by definition, asynchronous. All you can do is return void and take a callback as argument (just like $.ajax() does), or return a Promise or an Observable. - JB Nizet
@JBNizet It works, I added a callback function. - Albert Gao

1 Answers

1
votes

You can't just return a value as the ajax request is async. There are a few options:

(1) Use async function:

async function callAPI(): JSONObject {
    return new Promise<JSONObject>(resolve => {
        $.ajax().done((data, textStatus, jqXHR) => {
            resolve(data);
        });
    });
}

(2) Return a promise:

function callAPI(): Promise<JSONObject> {
    return new Promise<JSONObject>(resolve => {
        $.ajax().done((data, textStatus, jqXHR) => {
            resolve(data);
        });
    });
}

(3) Pass a callback instead of retuning a value:

function callAPI(cb: (JSONObject) => void): void {
    $.ajax().done((data, textStatus, jqXHR) => {
        cb(data);
    });
}