首页 > 解决方案 > 异步不同步

问题描述

我有一个按钮,点击后会生成一个 http.get,然后显示一些数据,尽管我的 async/await 似乎没有正确同步。

由于我还没有完全弄清楚的原因,this.tabRows = file.contents将在loadDateFolderFileContents()完成之前调用。我错过了await某个地方吗?

  async ngAfterViewInit() {
    if (!this.drawn) {
        if(!file.contents){
          await this.dataLakeService.loadDateFolderFileContents(file.parentFolder);
        }
        this.tabRows = file.contents;
        this.redraw();
    }
  }

  public async loadDateFolderFileContents(dateFolder: folder) {
    await date.files.map(async file => {
      file.contents = await this.getFileContents(dateFolder.name, file.name);
    });
  }

  public async loadDateFolderFileContents(dateName: string, fileName: string): Promise<any> {
    var url = this.buildUrl(dateName, fileName);
    var fileContents = {};
    await this.http.get<any>(url).toPromise()
      .then(contents => { 
        fileContents = contents; 
      })
      .catch(e => { 
        console.log(`Error retreiving file contents from url ${url}. Exception:${e}`); 
      });
    return fileContents;
  }

标签: javascriptangulartypescriptasynchronous

解决方案


map 不是异步的,所以不是:

await date.files.map(async file => {
...

尝试

await Promise.all(date.files.map(async file => {
...)

推荐阅读