[英]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.