【问题标题】:Async / Await does't hit code inside async {} [duplicate]Async / Await 不会在 async {} [重复] 中命中代码
【发布时间】:2020-08-21 15:30:17
【问题描述】:

我尝试使用异步/等待数据库加载来实现加载微调器,但无法在我的异步方法中命中代码。 我的数据加载看起来像这样

getServerList(){
    this.http.get('XXXX')
    .map((data : Response) =>{
      return data.json() as MyObject[];
    }).toPromise().then(x => {
      this.serverList = x;
    })
  }

我的组件内部的功能是

    async () => {

      try {
        await this.serverListService.getServerList()
      }catch{}
    }

首先,我有一个警告告诉我,我的 await 关键字没有用,因为没有什么可以等待。所以我决定像这样在我的数据加载中添加一个异步关键字

async getServerList(){
    this.http.get('http://localhost:6875/api/ServerList_Base')
    .map((data : Response) =>{
      return data.json() as ServerListBase[];
    }).toPromise().then(x => {
      return x;
    })
    return this.serverList
  }

所以现在我的 await 很有用,但我的问题是代码永远不会在我的异步括号内。我的意思是里面的代码

async () => {}

从未被执行,我不知道为什么。我试图从构造函数/从 ngAfterViewInit 的 nginit 中加载它,但没有任何效果

而且当我尝试像这样删除这些异步括号时

 async loadDataFromDB(){

    await this.serverListService.getServerList()
    this.dataSource  = new MatTableDataSource()
      this.dataSource.paginator = this.paginator;
      this.dataSource.sort = this.sort;
      this.showSpinner = false;
}

在转到第二行“this.dataSource”之前不会等待 getServerList()... 我习惯在 c# 中使用 async/await,也许我错过了一些 angular 的东西。 提前致谢

【问题讨论】:

  • getServerList()的第一个版本,将return添加到第一行(return this.http.get('XXXX') ...)。你不能等待不返回承诺的东西。
  • 你为什么要把 promise 和 async/await 混在一起,挑一个来用吧
  • getServerList 需要返回承诺:async getServerList(){ return this.http.get('http://localhost:6875/api/ServerList_Base')...
  • .toPromise().then(x => { return x; }) 实际上什么也没做
  • @liam 好的,谢谢,我想我需要更深入地了解一下 promise 的工作原理..

标签: angular asynchronous async-await angular7


【解决方案1】:

您的getServerList 应该是这样的

getServerList(): Observabe<MyObject[]>{
    return this.http.get('XXXX')
    .pipe(
       map((data : Response) =>{
          return data.json() as MyObject[];
       })
    );
  }

然后你就这样消费它:

getServerList().subscribe((data: MyObject[]) => {
   
});

我建议你阅读docs on observables on the angular web page 和前面提到的How do I return the response from an asynchronous call? 问题。

Promises、async/await 和 observables 都是针对同一问题的类似解决方案,但它们的工作方式各不相同。您的代码目前混合了所有这 3 个。有多种方法可以实现上述目标,但我建议您选择其中一种解决方案并坚持使用,而不是将它们混为一谈。将它们混合在一起只会使您的代码混乱。

【讨论】:

    猜你喜欢
    • 2020-06-06
    • 1970-01-01
    • 1970-01-01
    • 2019-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-02
    • 1970-01-01
    相关资源
    最近更新 更多