Search code examples
javascripttypescriptpromisees6-promise

Get a value from 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
}

Solution

  • 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