Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a value inside a Promise Typescript

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
}
like image 965
Rjk Avatar asked Aug 19 '16 06:08

Rjk


People also ask

How do I return a value from promise react?

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 .

Can a promise return an object?

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.


2 Answers

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

  • TypeScript Deep Dive docs
like image 71
basarat Avatar answered Oct 06 '22 00:10

basarat


Try this

functionB(): string {
   return this.functionA().then(value => ... );
}
like image 33
Suren Srapyan Avatar answered Oct 06 '22 00:10

Suren Srapyan