【发布时间】:2017-11-24 17:43:37
【问题描述】:
我有一个嵌套的 for 循环,内部循环也以角度 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 调用仍处于挂起状态。
【问题讨论】:
-
似乎
promises在这里为您服务,更准确地说是Promise.all。或者您可以通过在回调中增加一个变量并测试是否所有响应都到达了老派的方式,这样您就可以触发其余的代码(所有这些都在回调中,除了不需要在步骤) -
如果我在
getSubs服务调用中打印appCounter变量,它打印的值等于this.list的大小,因为即使是第一次服务调用,外部循环也会被执行并且appCounter会递增。 -
计数器增量及其值的测试必须在异步调用的回调中才能工作
标签: javascript angular typescript synchronization