Observable 用 async\await 代替 Promise

我有一个返回承诺并在循环中使用 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 方法?


慕斯王
浏览 130回答 1
1回答

Smart猫小萌

results在对 进行另一个异步调用之前,您希望等到数组填充完毕groupingGuaranteesMetaDataCategories()。forkJoin()可以用来做到这一点。getFilteredGuaranteesByPermissions(): Promise<GuaranteesMetaData[]> {&nbsp; const result = [];&nbsp; for (const guarantees of this.guaranteesMetaData) {&nbsp; &nbsp; &nbsp; result.push(&nbsp; &nbsp; &nbsp; &nbsp; from(this.permissionService.hasReadPermission(guarantees.key)).pipe(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; map(hasPermission => hasPermission ? guarantess : null)&nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; &nbsp; );&nbsp; }&nbsp; return forkJoin(result).subscribe((result) => {&nbsp; &nbsp; result = result.filter(value => value !== null);&nbsp; &nbsp; return this.groupingGuaranteesMetaDataCategories(result);&nbsp; });}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript