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
}
To get promise value in React and JavaScript, we can use await . to create the getAnswer function that calls fetch with await to get the response data from the promise returned by fetch . Likewise, we do the same with the json method. And then we call setAns to set the value of ans .
Returns a new Promise object that is resolved with the given value. If the value is a thenable (i.e. has a then method), the returned promise will "follow" that thenable, adopting its eventual state; otherwise, the returned promise will be fulfilled with the value.
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;
}
Try this
functionB(): string {
return this.functionA().then(value => ... );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With