gpt4 book ai didi

javascript - typescript 循环结束时的回调

转载 作者:行者123 更新时间:2023-11-28 17:34:06 24 4
gpt4 key购买 nike

我对这段代码感到绝望。

getSumOfSpecificDayWeek(daysMonth: any, callback: any){
var data = [];
var that = this;
daysMonth.forEach(function(day){
that.statsService.getData(that.userid, day).subscribe(async (res: any) => {
data = JSON.parse(JSON.stringify(res));
console.log(that.data);
that.data = that.data.map( function(v, i) {
return v + data[i];
});
});
});
callback("this should be at the end");
}

这里我正在做的是从服务器获取数组并将其汇总到每个组件的数据中,这工作正常,但最后我想平均结果,此时此刻我只是调用回调来显示一条消息来检查它是否最终发生,但是没有,在循环开始求和之前会显示“这应该在末尾”。

  mycallback(arg: any){
console.log(arg);
}

这是对该方法的主要调用

this.getSumOfSpecificDayWeek(daysMonth, this.mycallback);

最佳答案

更多的 RxJS,但更优雅的方式:

getSumOfSpecificDayWeek(daysMonth: any, callback: any){
var data = [];
var that = this;
let getCalls = []; // <--- This will contain all of your observables.
daysMonth.forEach(function(day){
const observable = that.statsService.getData(that.userid, day);
getCalls.push(observable); // <--- Add the current observable to the array.
observable.subscribe(async (res: any) => {
data = JSON.parse(JSON.stringify(res));
console.log(that.data);
that.data = that.data.map( function(v, i) {
return v + data[i];
});
});
});
// And here, you can use `callback`:
Observable.forkJoin(...getCalls).subscribe(results => {
callback("this should be at the end");
});
}

关于javascript - typescript 循环结束时的回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49558665/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com