与 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/