Get a value inside a Promise Typescript
47,118
Solution 1
How do I unwrap/yield the value inside that promise
You can do it with async
/await
.Don't be fooled into thinking that you just went from async to sync, async await it is just a wrapper around .then
.
functionA(): Promise<string> {
// api call returns Promise<string>
}
async functionB(): Promise<string> {
const value = await this.functionA() // how to unwrap the value inside this promise
return value;
}
Further
Solution 2
Try this
functionB(): string {
return this.functionA().then(value => ... );
}
Author by
Rjk
Updated on August 03, 2022Comments
-
Rjk almost 2 years
One of function inside a typescript class returns a
Promise<string>
. How do I unwrap/yield the value inside that promise.functionA(): Promise<string> { // api call returns Promise<string> } functionB(): string { return this.functionA() // how to unwrap the value inside this promise }
-
Rjk over 7 yearsstill returns a
Promise<string>
-
Suren Srapyan over 7 years@Rjk in the
then
function thevalue
is thestring
-
Rjk over 7 yearsyes, I understand that. I need to return the
string
, instead ofPromise<string>
. -
Suren Srapyan over 7 years@Rjk you can't return string.You must return promise and in the calling function assign the value in the
then
to your variable -
tedcurrent over 7 years
functionA
is asynchronous and therefore there's no chance you will be able to return a singlestring
value from it viafunctionB
. You might get by by passing acallback
tofunctionB
, but that would defeat the purpose of having thefunctionB
in between. @SurenSrapyan's answer is correct and you should do further handling of thestring
within.then()
. -
Amos Long about 5 years@SurenSrapyan I downvoted this answer because you didn't answer the Rjk's question; you answered a different question, then in your comments told Rjk that the original question was wrong.
-
Samyak Bhuta almost 4 years* The link no more available and redirects to home page. It also feels very promotional (although, author might have good intent at heart). Request the admins to look into it.
-
basarat almost 4 yearsI do link to docs I've written but I am careful to do it under
more
/further
section. To decrease the promotional feel I've added to the answer body 🌹 -
thatguy1155 almost 4 yearsI've also had the same problem by doing as is suggested above but then calling functionB in a synchronous way. Make sure it's still async() => { value = await functionB() } and so on for any other function when you need the result of the promise.
-
Rod Hartzell about 3 yearsGreat answer. This helped me understand async/await in TypeScript.