javascript - Obtener un valor de un Promise en Typescript
Una de las funciones dentro de una clase de TypeScript devuelve un Promise<string>. ¿Cómo puedo desempaquetar/obtener el valor dentro de esa promesa?
functionA(): Promise<string> {
// api call returns Promise<string>
}
functionB(): string {
return this.functionA() // how to unwrap the value inside this promise
}
Respuesta #1
¿Cómo puedo desempaquetar/obtener el valor dentro de esa promesa?
Puedes hacerlo con async/await. No te dejes engañar pensando que simplemente pasaste de async a sync, async await es solo un envoltorio alrededor de .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;
}
Más
- Documentos de TypeScript Deep Dive
Respuesta #2
Intenta esto
functionB(): string {
return this.functionA().then(value => ... );
}
