【问题标题】:How to use async await with http response如何使用带有 http 响应的异步等待
【发布时间】:2020-06-09 16:51:53
【问题描述】:

我正在尝试将数据加载到前端的表中,但我需要提供的数据来自我调用的 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())
      });
    }
  }

【问题讨论】:

  • 为什么你有2个ngOnInit函数或者这完全是另一种类型?
  • 其中一些函数位于单独的文件中。这两个 ngOnInit 位于两个不同的文件中。
  • @Igor 这帮助我更好地理解了 async-await,但我仍然没有看到我在代码中做错了什么。当我调用await data;await data.length; 时,它仍然会抛出相同的错误,就像它试图查找未定义的长度而不是数组的长度一样。
  • 仅供参考 for (i in blah.length) 不是有效的 for 循环。

标签: angular asynchronous async-await angular-httpclient


【解决方案1】:

您需要有一个承诺才能使用 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;
  }

【讨论】:

    猜你喜欢
    • 2017-10-18
    • 2018-06-03
    • 2011-09-03
    • 2013-08-29
    • 2019-05-23
    • 2017-01-29
    • 2020-12-03
    • 2017-12-17
    • 1970-01-01
    相关资源
    最近更新 更多