如何使用 async await 和 http 响应

How to use async await with http response

我正在尝试将数据加载到前端的 table 中,但我需要提供的数据来自 API,我将其调用并存储在数组中,就像这样[=15] =]

ngOnInit() {
    this.jsonStored = [];
    const observables = this.data.map(data =>
      this.time.getPunchDataWeek(data.id)
    );
    forkJoin(observables).subscribe(
      results => {
        this.jsonStored.push(results);
      },
      err => {
        console.error(err);
      },
      () => {
        this.totalToday = this.time.getTotalEmpToday(this.jsonStored[0][0]);
        this.totalWeek = this.time.getTotalEmpWeek(this.jsonStored[0][0]);
      }
    );
  }

我知道这是异步发生的,所以我需要等到请求完成才能将我的 jsonStored 数组传递给其他函数来处理数据,然后继续将其加载到前端的 table 中。我相信我应该使用 async-await 来做到这一点,但我不确定我是否做对了。

我刚开始写我的代码,但在测试之后,我得到了这个错误

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'length' of undefined

到目前为止,这是我的代码

async getTotalData(data: any) {
    await data;
    let i: string | number;
    for (i in data.length) { // <----------------- ERROR REFERS TO THIS LINE
      console.log(i);
      console.log(data[i]);
    }
    return 0;
  }
async getActual(day: string | number | Date) {
    day = new Date(day);

    let response = await this.time.getTotalData(this.jsonStored[0]);
    return 0;
  }
async ngOnInit() {
    for (this.i in this.dash.weekdays) {
      this.SHIFTSTATS_DATA.push({
        day: this.dash.weekdays[this.i],
        requested: 2,
        provided: 2,
        ontime: 2,
        actual: await this.dash.getActual(new Date())
      });
    }
  }

您需要有承诺才能与 async/await 合作。

async getTotalData(data: Promise<any[]>) { // <- Data needs to be a promise

    // assuming that data is a promise and resolve an array, you have to store
    // the result. In this case, I store the result in myArrayResolved
    const myArrayResolved: any[] = await data;

    let i: string | number;

    for (i in myArrayResolved.length) { // <- now I do my array stuff
      console.log(i);
      console.log(data[i]);
    }
    return 0;
  }