hea*_*kit 6 javascript asynchronous promise async-await typescript2.0
我有一种情况,我需要对异步方法的结果调用异步方法。
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();
Run Code Online (Sandbox Code Playgroud)
有没有一种好方法可以避免双重等待的需要?我想我只想做await container.getChild().getText();。在 TypeScript 中创建 API 的正确方法是什么,它允许我链接返回 promise 的方法,然后通过一个 await 等待结果?
编辑:澄清一下,这更像是一个 API 设计问题。有没有更好的模式来做我想做的事情(在异步方法返回的对象上调用异步方法)?即使这意味着做一些完全不同的事情?
有没有办法更好地设计我的 API 以便用户不需要双重等待?即使这意味着彻底改变我的例子的结构。
您不能使getResult异步,它需要立即返回一个Result实例,以便可以在其上调用进一步的方法。你的例子有点奇怪,因为getChild根本不需要异步。但是让我们假设它是,并且做了一些重要的事情。
然后你可以写
class Parent {
private async getChild(): Promise<Child> {
… // whatever
}
getResult(): Result {
return new Result(this.getChild())
}
}
class Result {
constructor(p: Child) {
this.promise = p;
}
async getText(): Promise<string> {
return (await this.promise).getText();
}
}
Run Code Online (Sandbox Code Playgroud)
现在可以parent.getResult().getText()直接打电话了。基本上,Result充当类的代理包装器Child,同时进行等待。也许在您的实际架构中,您甚至可以this.promise一步避免并完成子和文本访问。
然而,通常这是不值得的。只需让您的来电者await每走一步。
| 归档时间: |
|
| 查看次数: |
4718 次 |
| 最近记录: |