Reputation: 129
I have a method that return promise and works with async/await concept in loop.
async getFilteredGuaranteesByPermissions(): Promise<GuaranteesMetaData[]> {
const result = [];
for (const guarantees of this.guaranteesMetaData) {
if (await this.permissionService.hasReadPermission(guarantees.key)) {
result.push(guarantees);
}
}
return this.groupingGuaranteesMetaDataCategories(result);
}
groupingGuaranteesMetaDataCategories(guarantees: GuaranteesMetaData[]): GuaranteesMetaData[] {
return _.groupBy(guarantees, 'category');
}
hasReadPermission
return boolean
groupingGuaranteesMetaDataCategories
return array.
I tried use reduce, forkJoin, map, but I cant understand how to rewrite async/await to Observable correct that is not subscribe to every hasReadPermission method in loop?
Upvotes: 3
Views: 437
Reputation: 6643
You want to wait till results
array is populated before making another asynchronous call to groupingGuaranteesMetaDataCategories()
.
forkJoin() can be used to do that.
getFilteredGuaranteesByPermissions(): Promise<GuaranteesMetaData[]> {
const result = [];
for (const guarantees of this.guaranteesMetaData) {
result.push(
from(this.permissionService.hasReadPermission(guarantees.key)).pipe(
map(hasPermission => hasPermission ? guarantess : null)
)
);
}
return forkJoin(result).subscribe((result) => {
result = result.filter(value => value !== null);
return this.groupingGuaranteesMetaDataCategories(result);
});
}
Upvotes: 4