我正在以承诺获取数据。我使用这个回调函数循环遍历该值。
selectedAppIdCalculator() {
this.fetchData2().then( value => {
console.log("value: ", value);
for (let app of value) {
console.log("in for loop");
}
});
}
响应值不为null,因为它首先记录该值。该值是一个带有json对象的数组。
但for循环从未执行过。为什么呢?
在调试模式中,我注意到一些奇怪的东西。
但是当正常运行时,它通常会记录响应值。我真的很困惑。
答案 0 :(得分:1)
好的所有问题是你在解析前不要等待fetchAppData响应。
您使用this.reduceAppList作为空数组在100ms后解决您的承诺。 稍后收到fetchAppData响应时,您将填充此数组。 这就是为什么数据显示在控制台中(因为控制台使用Object引用来显示数据)而不是在调试模式下(因为断点是在填充数组之前设置的。
您应该将fetchData2函数更改为:
fetchData2() {
this.reducedAppList = [];
this.httpService.fetchAppData().then(response => {
this.appList = this.httpService.statistics;
for (const app of this.appList) {
if (app.appMailings !== null) {
this.reducedAppList.push(app);
}
}
return this.reducedAppList;
});
}
答案 1 :(得分:0)
您fetchData2
的决心似乎超出了promise
。如果是,则在任何数据可用之前调用resolve
,并且需要超出for
的范围。
这是因为async
性质,您的决议在请求完成之前完成,而是返回初始值reducedAppList
应该是这样的:
for (const app of this.appList) {
// logic ommitted
}
resolve(this.reducedAppList); // move inside the `.then(response => ....`