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 => ... );
}
Share:
47,118
Rjk
Author by

Rjk

Updated on August 03, 2022

Comments

  • Rjk
    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
    Rjk over 7 years
    still returns a Promise<string>
  • Suren Srapyan
    Suren Srapyan over 7 years
    @Rjk in the then function the value is the string
  • Rjk
    Rjk over 7 years
    yes, I understand that. I need to return the string, instead of Promise<string>.
  • Suren Srapyan
    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
    tedcurrent over 7 years
    functionA is asynchronous and therefore there's no chance you will be able to return a single string value from it via functionB. You might get by by passing a callback to functionB, but that would defeat the purpose of having the functionB in between. @SurenSrapyan's answer is correct and you should do further handling of the string within .then().
  • Amos Long
    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
    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
    basarat almost 4 years
    I 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
    thatguy1155 almost 4 years
    I'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
    Rod Hartzell about 3 years
    Great answer. This helped me understand async/await in TypeScript.