在TypeScript中使用async/await进行方法链接 [英] Method chaining with async/await in TypeScript

查看:1037
本文介绍了在TypeScript中使用async/await进行方法链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到一种情况,我需要根据异步方法的结果调用异步方法.

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();

是否有一个很好的方法来避免需要两次等待?我想我只想做await container.getChild().getText();.用TypeScript制作API的正确方法是什么,该方法将允许我链接返回promise的方法,然后一次等待就可以等待结果?

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?

为澄清起见,这更多是关于API设计的问题.有没有更好的方式来做我想做的事情(在异步方法返回的对象上调用异步方法)?即使这意味着做一些完全不同的事情?

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?

推荐答案

有没有一种方法可以更好地设计我的API,从而使用户不需要双重等待?即使这意味着彻底改变我的示例结构.

Is there a way to design my API better so that users won't need the double await? Even if it means changing the structure of my example drastically.

您不得使getResult异步,它需要立即返回Result实例,以便可以在其上调用更多方法.您的示例有点奇怪,因为getChild根本不需要完全异步.但是,让我们假设它确实是重要的.

You must not make getResult asynchronous, it needs to return a Result instance right away so that further methods can be called on it. Your example is a bit weird since getChild doesn't really need to be asynchronous at all. But lets assume it is, and does some important.

然后您可以写

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();
  }
}

现在您可以直接致电parent.getResult().getText().基本上,Result充当同时执行两个等待的Child类的代理包装.也许在您的实际体系结构中,您甚至可以避开this.promise并一步一步进行子级和文本访问.

Now you can call parent.getResult().getText() directly. Basically, Result acts as a proxy wrapper around the Child class that does both the awaits. Maybe in your actual architecture you can even avoid the this.promise and do the child and text accesses in one step.

但是,通常这是不值得的.只需让呼叫者await每一步.

However, usually this is not worth it. Just let your caller await each step.

这篇关于在TypeScript中使用async/await进行方法链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆