【发布时间】:2021-11-19 17:21:02
【问题描述】:
有什么帮助吗?
let notificationsMessages = []
countries.forEach((country: any) => {
this.isActiveCountry(country.isActive).subscribe((data) => { // // CALL #1 TO API
country.serverId = data.serverId;
this.uploadPhotoToApi(country.fileSource).subscribe((response) => { // CALL #2 TO API
// server return the uploaded file ID
country.serverFileID = response.serverFileId;
this.sendCountryToApi(country).subscribe((response) => { // CALL #3 TO API
this.countriesTable.delete(country.id).then(() => {
// Delete the uploaded country from local database
// if is the last country EMIT EVENT
}, (error) => {
// if is the last country EMIT EVENT
notificationsMessages.push(error); // Error to delete country from indexedDB
});
}, (error) => {
// if is the last country EMIT EVENT
notificationsMessages.push(error); // // Error to upload country to API
});
}, (errorCode) => {
// if is the last country EMIT EVENT
notificationsMessages.push(error); // Error on sending file to API
});
}, (error) => {
// if is the last country EMIT EVENT
notificationsMessages.push(error); // // Error on country identification
});
});
处理完所有country 列表后,如何发出事件?
我需要知道有多少国家上传成功,有多少没有。
例如,如果我有一个包含 50 个国家/地区的列表,则在处理最后一个国家/地区时,我想发出一个包含 2 个数组的事件……如下所示: 成功:[countryId1, countryId2...] 错误:['Country Id 2 failed on upload', 'Country Id 10 failed on file upload']
所有这 3 个调用都是依赖的,必须按该顺序执行……我无法更改此流程。 我应该在 CALL #3 成功以及所有错误函数上发出事件吗? 谢谢!
【问题讨论】:
-
尝试 switchMap 运算符
-
以及我如何知道 forEach 已完成并且所有项目都已处理?
-
您可以使用 deps 构建一个流,一旦流完成,您的所有项目都会被处理
标签: javascript angular typescript rxjs functional-programming