这是我的代码,我从一个空数组开始,想要调用一个对填充后的数组做一些工作的服务。我使用对服务的两次调用来填充数组,这些服务调用一个API来接收要插入到数组中的元素。
我正在尝试使用Promise来确保我的数组subscribers
充满了正确的订阅者对象,但是即使最终确实将对象添加到订阅者数组中,过程processSubscribers方法也总是收到一个空数组(如所见)在chrome调试中)。
doSomething(){
const subscribers: ISubscriber[] = [];
const promises = [];
this.selectedChildren.forEach(child => {
promises.push(this.serviceA.getSubscribers(child.id).subscribe( (subs: ISubscriber[]) => {
subs.forEach(s => {
subscribers.push(s);
});
}));
});
this.selectedSubscribers.forEach(sub => {
promises.push(this.serviceB.getSubscriber(sub.subscriberId).subscribe( (sub: ISubscriber) => {
subscribers.push(sub);
}));
});
// subscribers is always empty when this call is made
// since above code hasn't finished executing
Promise.all(promises).then( a => {
this.serviceC.processSubscribers(this.id, subscribers).subscribe( id => {
this.toastr.success('Success!');
});
});
}
答案 0 :(得分:0)
这行代码的结果是预订而不是承诺
this.serviceA.getSubscribers(child.id).subscribe( (subs: ISubscriber[]) => {
subs.forEach(s => {
subscribers.push(s);
})
这意味着您的promise
数组不包含诺言,这就是promise.all
不起作用的原因
您可以做到
promises.push(this.serviceB.getSubscriber(sub.subscriberId).toPromise())
或
promises.push(this.serviceB.getSubscriber(sub.subscriberId).toPromise().then(x => ... ))