在 Promise Typescript 中获取一个值
Get a value inside a Promise Typescript
typescript 中的函数之一 class returns a Promise<string>
。我如何 unwrap/yield 该承诺中的价值。
functionA(): Promise<string> {
// api call returns Promise<string>
}
functionB(): string {
return this.functionA() // how to unwrap the value inside this promise
}
试试这个
functionB(): string {
return this.functionA().then(value => ... );
}
How do I unwrap/yield the value inside that promise
你可以用 async
/await
来完成。不要误以为你只是从异步到同步,async await 它只是 [=13= 的包装器].
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 中的函数之一 class returns a Promise<string>
。我如何 unwrap/yield 该承诺中的价值。
functionA(): Promise<string> {
// api call returns Promise<string>
}
functionB(): string {
return this.functionA() // how to unwrap the value inside this promise
}
试试这个
functionB(): string {
return this.functionA().then(value => ... );
}
How do I unwrap/yield the value inside that promise
你可以用 async
/await
来完成。不要误以为你只是从异步到同步,async await 它只是 [=13= 的包装器].
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;
}