gpt4 book ai didi

javascript - Typescript 在嵌套 for 循环完成后执行代码

转载 作者:行者123 更新时间:2023-11-30 20:57:50 27 4
gpt4 key购买 nike

我有一个嵌套的 for 循环,内部循环也在 Angular 2 中进行服务调用

public populateData: any[] = [];

let appCounter = 0;
this.list.forEach(data => { <---- outer loop
this.service.getSubs(data.id).subscribe(res => { <---- backend call to get data
let subscriptions = res.subscriptions;

subscriptions.forEach(subscription => {
if(condition){
this.populateData.push(subscription);
}
});
});
appCounter++;
if(appCounter == this.list.length){
console.log('--------- subscriptionList ----------');
console.log(this.populateData);
}
});

我想在 populateData 变量通过完全执行外循环填充后调用一个方法。

目前,它在控制台中为我提供了空数组,因为外部循环已完全执行,而内部 HTTP 调用仍未决。

最佳答案

您可能会遇到 forkJoin 的运气:

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/forkJoin';

public populateData: any[] = [];
public observables: any[] = [];

this.list.forEach(data => {
this.observables.push(this.service.getSubs(data.id));
});

Observable.forkJoin(this.observables)
.subscribe(res => {
res.forEach((element:any) => {
let subscriptions = element.subscriptions;
subscriptions.forEach(subscription => {
if(condition){
this.populateData.push(subscription);
}
});
console.group('subscription list');
console.log(this.populateData);
});
})

关于javascript - Typescript 在嵌套 for 循环完成后执行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47469482/

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