【问题标题】:functions that return promises must be async返回承诺的函数必须是异步的
【发布时间】:2019-04-25 08:34:46
【问题描述】:

当我在我的代码上运行 tslint 时,出现以下错误

functions that return promises must be async

这里是代码

private doSomething(): void {
    fetch(myUrl)
        .then((rsp: Response) => rsp.text()) // <-- gives error
        .then(txt => this.txt = txt);
}

现在不知道如何解决这个问题,因为代码运行得很好!有什么建议吗?

【问题讨论】:

  • @Kraylog no...这不是 fetch() API 的工作方式。 rsp.text() 回报承诺
  • rsp 是来自Fetch 的响应,所以我觉得不能同步
  • response.text() 返回一个承诺。 developer.mozilla.org/en-US/docs/Web/API/Body/text;
  • 您是否使用了正确的响应类型?

标签: javascript asynchronous promise async-await tslint


【解决方案1】:

此错误消息是由 tslint 规则 promise-function-async 引起的。

您可以通过在箭头函数表达式上添加异步来遵守此规则:

.then(async (rsp: Response) =&gt; rsp.text())

【讨论】:

  • 如果我这样做,我会收到以下错误:TSLint: Spaces before function parens are disallowed (space-before-function-paren)
  • 删除 async 和开头括号之间的空格。您还可以配置您的编辑器/linter 以自动修复其中一些错误。
猜你喜欢
  • 1970-01-01
  • 2021-02-04
  • 2022-01-26
  • 1970-01-01
  • 2020-01-11
  • 1970-01-01
  • 2018-12-22
相关资源
最近更新 更多