Get a value inside a Promise Typescript

穿精又带淫゛_ 提交于 2020-06-14 04:20:06

问题


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
}

回答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

  • TypeScript Deep Dive docs



回答2:


Try this

functionB(): string {
   return this.functionA().then(value => ... );
}


来源:https://stackoverflow.com/questions/39032333/get-a-value-inside-a-promise-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!