在Promise Typescript中获取值 [英] Get a value inside a Promise Typescript

查看:564
本文介绍了在Promise Typescript中获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

打字稿类中的一个函数返回 Promise< string>

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
}


推荐答案


如何解包/获得其中的值承诺

How do I unwrap/yield the value inside that promise

您可以使用 async / 不要误以为您刚刚从异步转到了同步,异步等待只是对的包装。然后

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;
}



进一步




  • TypeScript深入研究文档

  • Further

    • TypeScript Deep Dive docs
    • 这篇关于在Promise Typescript中获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆