简体   繁体   中英

Observable instead Promise with async\await

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?

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);
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM