I have a situation where I need to call an async method on the result of an async method.
class Parent {
constructor(private child: Child) { }
private getChild(): Promise<Child> {
return Promise.resolve(this.child);
}
async getResult(): Promise<Child> {
return await this.getChild()
}
}
class Child {
getText(): Promise<string> {
return Promise.resolve('text');
}
}
let child = new Child();
let container = new Parent(child);
let printText = async () => {
await (await container.getResult()).getText();
}
printText();
Is there a good way to avoid the need to double await? I think I'd like to just do await container.getChild().getText();. What's the right way to make an API in TypeScript that will allow me to chain methods that return promises and then wait for the result with a single await?
EDIT: To clarify, this is more of an API design question. Is there a better pattern for doing what I'm trying to do (call an async method on an object returned by an async method)? Even if it means doing something totally different?
await, use.then.awaitwith areturnand that might do what you want.thentwice as well. You can writeconst result = await container.getResult(); await result.getText();.awaitwithreturn:-)await container.getChild().getText();syntax is not possible whengetChildreturns a promise, as promises don't have agetTextmethod. End of story.