错误: Type 在 ES5/ES3中不是一个有效的异步函数返回类型,因为它没有引用一个承诺兼容的构造函数

我用 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: 在 ES5/ES3中,输入‘ boolean’不是有效的异步函数返回类型,因为它不引用与  约()兼容的建构函式值。

我以前在其他应用程序中使用过异步/等待,但没有遇到过这种情况。

更新: 我想要回答的问题是: 如何让“ isLoggedIn”函数返回一个布尔值?

75910 次浏览

An async function can ONLY return a promise by definition - all async functions return promises. It can't return a boolean.

That's what TypeScript is telling you. The async function can return a promise that resolves to a boolean.

The value that you return inside your async function becomes the resolved value of the promise that the async function returns. So, the return type for your async function is a promise (that resolves to a boolean).

The caller of isLoggedIn() will have to either use .then() with it or await with it.

export class LoginService {


async isLoggedIn(): Promise<any> {
const r = await this.http.get('http://localhost:3000/api/user/isLoggedIn').toPromise();
return r.body;
}


}

If your endpoint /api/user/isLoggedIn returns only a boolean value, you should just be able to use below by casting the http get method. But indeed you can only return a promise from an async function.

export class LoginService {
async isLoggedIn(): Promise<boolean> {
return this.http.get<boolean>('http://localhost:3000/api/user/isLoggedIn').toPromise();
}
}

You could have an async function that consumes isLoggedIn() like this:

async doSomething() {
const loggedIn: boolean = await service.isLoggedIn();
if (loggedIn) {
doThis();
}
}

Which would be called like this

await doSomething();

The return type should be Promise

/* sync */ isLoggedIn(): boolean
async isLoggedIn(): Promise<boolean>

async functions return a Promise (mandatory by virtue of being async), and you indicate that the promise will resolve to a boolean