在 Promise Typescript 中获取一个值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39032333/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:45:54  来源:igfitidea点击:

Get a value inside a Promise Typescript

javascripttypescriptpromisees6-promise

提问by Rjk

One of function inside a typescript class returns a Promise<string>. How do I unwrap/yield the value inside that promise.

打字稿类中的一个函数返回一个Promise<string>. 我如何解开/产生该承诺中的价值。

functionA(): Promise<string> {
   // api call returns Promise<string>
}

functionB(): string {
   return this.functionA() // how to unwrap the value inside this  promise
}

回答by basarat

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.

你可以用async/await来做。不要误以为你只是从异步到同步,异步等待它只是一个包装器.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

更远

回答by Suren Srapyan

Try this

试试这个

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