javascript - async void 的 typedef 是什么

标签 javascript angular typescript asynchronous

this question 有点相关,但有所不同。

TSLint 提示此代码,因为它需要 typedef:

  private async getTranslations() {
    // this.translations is a public variable used by the html
    this.translations = await this._languageService.getTranslations('Foo');
  }

我已将其更新为

private async getTranslations() : void { ... }

这给了我错误:

type 'void' is not a valid async function return in ES5 because it does not refer to a pPromise-compatible constructor value

如何在不删除 async 关键字的情况下实现这一点?

最佳答案

type 'void' is not a valid async function return in ES5 because it does not refer to a pPromise-compatible constructor value

您收到错误,因为当您使用 async/await 时那么返回类型将是 Promise包装对象,因此函数返回类型应为 Promise<returntype> ,在你的情况下它将是

 private async getTranslations() : Promise<void> {
    // this.translations is a public variable used by the html
    this.translations = await this._languageService.getTranslations('Foo').toPromise();
  }

如果您使用的是 Angular,那么服务大多会返回 observable object ,因此需要将其转换为 promise通过调用 toPromise() 来获取对象调用函数(如果您不输入 toPromise 如果您在服务中使用 httpClient 来获取结果,则不会触发请求。)。

关于javascript - async void 的 typedef 是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51169038/

相关文章:

javascript - Angular 发布请求不起作用不起作用

javascript - 如何刷新我的 ng-repeat?

javascript - 当我们有闭包时,JavaScript 中是否需要原型(prototype)?

javascript - Formik 和 Material-UI

visual-studio-2012 - 如何改进我的 Visual Studio 2012 Typescript 工作流?

javascript - 正则表达式替换某些单词/字符之间的文本或空白

javascript - 如何将 Angular 集成到我当前的 Firebase node.js 项目中?

angular - 创建一个 Angular 库并在我的 Angular 项目中本地使用它

angular - 如何从指令访问主机组件?

typescript - IE11 Angular-CLI 源映射不工作