簡體   English   中英

如何在 http 響應中使用異步等待

[英]How to use async await with http response

我正在嘗試將數據加載到前端的表中,但我需要提供的數據來自一個 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]);
      }
    );
  }

我知道這是異步發生的,所以我需要等到請求完成才能將我的 jsonStored 數組傳遞給其他函數來處理數據並繼續將它加載到我的前端表中。 我相信我應該使用 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;
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM