我有一个返回承诺并在循环中使用 async/await 概念的方法。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'); }具有读取权限返回布尔值分组保证元数据类别返回数组。我尝试使用reduce、forkJoin、map,但我无法理解如何将async/await 重写为正确的Observable,即没有订阅循环中的每个hasReadPermission 方法?
1 回答
Smart猫小萌
TA贡献1911条经验 获得超7个赞
results在对 进行另一个异步调用之前,您希望等到数组填充完毕groupingGuaranteesMetaDataCategories()。
forkJoin()可以用来做到这一点。
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);
});
}
添加回答
举报
0/150
提交
取消