Albert Gao Albert Gao - 3 months ago 39
TypeScript Question

How return a object inside a done function while the function expected to have a return value in typescript?

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?

Answer

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