Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 错误:类型在ES5/ES3中不是有效的异步函数返回类型,因为它未引用与承诺兼容的构造函数_Angular_Promise - Fatal编程技术网

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

Angular 错误:类型在ES5/ES3中不是有效的异步函数返回类型,因为它未引用与承诺兼容的构造函数,angular,promise,Angular,Promise,我已经用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/

我已经用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中不是有效的异步函数返回类型,因为它未引用承诺兼容的构造函数值

我以前在其他应用程序中使用过async/await,但没有使用过它

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

异步函数只能根据定义返回承诺-所有异步函数都返回承诺。它不能返回布尔值

这就是TypeScript告诉你的。
async
函数可以返回解析为布尔值的承诺

async
函数中
返回的值成为
async
函数返回的承诺的解析值。因此,
async
函数的返回类型是promise(解析为布尔值)

isLoggedIn()
的调用者必须使用
.then()
等待它

export class LoginService {

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

}
导出类登录服务{
异步isLoggedIn():承诺{
const r=wait this.http.get('http://localhost:3000/api/user/isLoggedIn).toPromise();
返回r.body;
}
}

如果您的端点
/api/user/isLoggedIn
只返回一个布尔值,您应该可以通过强制转换http get方法来使用下面的方法。但实际上,您只能从异步函数返回承诺

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

await doSomething();

但是为什么我不能在“isLoggedIn()”函数中使用wait并返回布尔值呢?但是我不能使用wait,除非我使用async?但是如果我使用async,我不能返回布尔值?似乎有点“第二十二条军规”?您只能在将返回承诺的异步函数中使用wait。我们对javascript说,它是一个异步函数,将根据API响应返回。好的,感谢您的响应。我更新了我的问题,以更准确地反映我实际上在做什么。基本上,该函数执行一个异步api调用,我希望它等待/阻塞,直到获得一个具体的值(布尔值),然后返回布尔值。不是承诺。@user275801-正如我已经说过的,您使用
wait
.then()
和返回的承诺
xxx.isLoggedIn()。然后(bool=>{/*在此处使用值*/})
。有关更多信息,请参阅,并阅读有关使用
async
关键字声明的函数的更多信息。您可能需要升级到ES6。它明确说明你的假设是正确的。否则,何必费心等待,立即归还大坝承诺!
await doSomething();