我在TypeScript中编写了这个函数:
export class LoginService {
async isLoggedIn(): boolean {
const r = await this.http.get('http://localhost:3000/api/user/isLoggedIn').toPromise();
return r.body;
}
}
当我尝试运行Angular 6应用程序时,我收到此错误消息:
src / app / login.service.ts(28,23)中的错误:错误TS1055:类型'boolean'不是ES5 / ES3中的有效异步函数返回类型,因为它不引用与Promise兼容的构造函数值。
我以前在其他应用程序中使用了async / await而没有遇到过这种情况。
更新:我想回答的问题是:如何让“isLoggedIn”函数返回一个布尔值?
async
函数只能按定义返回一个promise - 所有async
函数都返回promise。它不能返回布尔值。
这就是TypeScript告诉你的。 async
函数可以返回一个解析为布尔值的promise。
你在return
函数中async
的值成为async
函数返回的promise的解析值。因此,async
函数的返回类型是一个promise(解析为boolean)。
isLoggedIn()
的来电者必须使用.then()
或await
。
export class LoginService {
async isLoggedIn(): Promise<any> {
const r = await this.http.get('http://localhost:3000/api/user/isLoggedIn').toPromise();
return r.body;
}
}
如果你的端点/api/user/isLoggedIn
只返回一个布尔值,你应该可以通过强制转换http get方法来使用下面的方法。但实际上你只能从异步函数返回一个promise。
export class LoginService {
async isLoggedIn(): Promise<boolean> {
return this.http.get<boolean>('http://localhost:3000/api/user/isLoggedIn').toPromise();
}
}
你可以有一个像这样消耗isLoggedIn()
的异步函数:
async doSomething() {
const loggedIn: boolean = await service.isLoggedIn();
if (loggedIn) {
doThis();
}
}
这将被称为这样
await doSomething();