简体   繁体   English

用 async\await 代替 Promise 可观察

[英]Observable instead Promise with async\await

I have a method that return promise and works with async/await concept in loop.我有一个返回 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');
    }

hasReadPermission拥有读取权限

return boolean返回 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?我尝试使用 reduce、forkJoin、map,但我无法理解如何将 async/await 重写为 Observable 正确,即不订阅循环中的每个 hasReadPermission 方法?

You want to wait till results array is populated before making another asynchronous call to groupingGuaranteesMetaDataCategories() .您想等到results数组被填充后再对groupingGuaranteesMetaDataCategories()进行另一个异步调用。

forkJoin() can be used to do that.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);
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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