简体   繁体   English

如何在 http 响应中使用异步等待

[英]How to use async await with http response

I am trying to load data into a table on my frontend but the data that I need to provide comes from an API which I call and store in an array like so我正在尝试将数据加载到前端的表中,但我需要提供的数据来自一个 API,我调用该 API 并将其存储在这样的数组中

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]);
      }
    );
  }

I know this happens asynchronously and so I need to wait until the request is completed to pass my jsonStored array into other functions to process the data and proceed to load it into my table on the frontend.我知道这是异步发生的,所以我需要等到请求完成才能将我的 jsonStored 数组传递给其他函数来处理数据并继续将它加载到我的前端表中。 I believe I'm supposed to do this using async-await but I'm not sure if I'm doing it right.我相信我应该使用 async-await 来做到这一点,但我不确定我是否做得对。

I just start writing my code but after testing it, I get this error我刚开始编写代码,但经过测试后,出现此错误

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

This is my code so far到目前为止,这是我的代码

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())
      });
    }
  }

You need to have a promise in order to work with async/await.您需要有一个承诺才能使用 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;
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM