foreach内部的Angular订阅不返回承诺



我正在foreach语句中执行逐行更新。我需要等到foreach循环中的所有项目都已更新,然后我需要进行一些最终确定。下面的方法对服务有效,但"wait.then"永远不会被命中。有更好的方法吗?

var wait = new Promise((resolve, reject) => {
this.myArray.Items.forEach(t => {
this.service.UpdateItems(t).subscribe(
() => {},
err => this.alert(err),
() => this.app.tick(),
);
});
});
wait.then(() => {
// Wait until the foreach finished
console.log(complete);
});

您不需要使用Promises。您可以使用forkJoin:执行类似操作

const sources = this.myArray.Items.map(item => {
return this.service.UpdateItems(item).pipe(
tap({
complete: () => this.app.tick(), // not sure for what you're using this
error: err => this.alert(err),
}),
);
});
forkJoin(sources)
.pipe(finalize(() => console.log('do something')))
.subscribe();

最新更新