【问题标题】:Method chaining with async/await in TypeScriptTypeScript 中使用 async/await 的方法链
【发布时间】:2017-10-03 08:42:17
【问题描述】:

我有一种情况,我需要对异步方法的结果调用异步方法。

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 的方法,然后通过一次 await 等待结果?

编辑:澄清一下,这更像是一个 API 设计问题。有没有更好的模式来做我想做的事情(在异步方法返回的对象上调用异步方法)?即使这意味着做一些完全不同的事情?

【问题讨论】:

  • 要在不使用await 的情况下链接承诺,请使用.then
  • 请注意,您的匿名函数会丢弃文本而不做任何事情。我不确定你是否有意这样做。您可以用return 替换外部await,这可能会满足您的需求。
  • 你在等待两件事,那么你为什么希望能够写一个等待呢?如果您使用的是 Promise,则还必须使用 then 两次。你可以写const result = await container.getResult(); await result.getText();
  • 将外部的await 替换为return :-)
  • await container.getChild().getText(); 语法在 getChild 返回承诺时是不可能的,因为承诺没有 getText 方法。故事结束。

标签: javascript asynchronous promise async-await typescript2.0


【解决方案1】:

有没有办法更好地设计我的 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();
  }
}

现在您可以直接拨打parent.getResult().getText()。基本上,Result 充当了 Child 类的代理包装器,它完成了这两个等待。也许在您的实际架构中,您甚至可以避免 this.promise 并一步完成子和文本访问。

但是,通常这是不值得的。只需让您的来电者await 每一步。

【讨论】:

  • 对,我的例子是人为的,并不需要异步。谢谢,这就是我要找的!我同意,只是让人们明确地await 可能更好,我只是想探索我的选择。
猜你喜欢
  • 1970-01-01
  • 2017-12-30
  • 2019-03-15
  • 1970-01-01
  • 2016-08-22
  • 2020-05-19
  • 2017-05-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多