user1464139
user1464139

Reputation:

How can I return a promise and data?

I have this function in javascript (typescript):

getRole = () => {
    return this.getData(EnumGetData.Role)
        .then((data) => { 
            this.role = data;
            // I want to do something with data here which is why 
            // I have the .then 
        });
}

Here's how I call the function:

return enumService.getRole()
    .then((results): void => {
       // I want to do something here with results
    });

The function works but as well as returning a success or fail I would like to also return data

Can someone give me some idea as to how I can do this?

Upvotes: 1

Views: 88

Answers (1)

Jaromanda X
Jaromanda X

Reputation: 1

Seems easy enough

getRole = () => {
    return this.getData(EnumGetData.Role)
        .then((data) => { 
            this.role = data;
            // I want to do something with data here which is why 
            // I have the .then 
            // "I would like to also return data"
            return data;
        });
}

Having re-read the question, I may have misunderstood ... you want getRole to return a Promise AND data? if so, then you can't do that, because if this.getData is asynchronous, then getRole can NOT return data (ignoring the fact that a function returns a single value)

contrary to popular misconception, a Promise does not make asynchronous code synchronous

(By your comments below, I see I did NOT misunderstand your question, and you have a grasp on how Promise's work)

BUT, if you were to

getRole().then(function(x) { 
    console.log(x); 
});

you'll find that x == data in the above code

Upvotes: 1

Related Questions