首页 > 解决方案 > 是否可以返回发出通过等待异步方法构造的数组的 Observable?

问题描述

我有下面的方法可以构建但不起作用:

  get screenShotResults$(): Observable<ScreenshotFile[]> { 
    return this.ngRedux.select<ICommunicationState>('communication').pipe(map(newState => {
      const ret: ScreenshotFile[] = [];
      newState.fileResults.forEach(async result => {
        if (result.type === 'SCREENSHOT') {
          const blob = await this.fileLocalStoreService.getAsync(result.id);
          if (blob !== undefined) {
            ret.push({id: result.id, blob: blob})
          }
        }
      });
      return ret;
    }));
  }

这个想法是它从 indexedDb 获取文件。但由于没有同步 API,我正在努力实现。

等待的方法如下所示:

  public async getAsync(key: string) {
    let blob: IFileBlob | undefined;
    blob = await this.db.files.get(key);
    if (blob === undefined) {
      return undefined
    }
    return blob.file;
  }

它正在使用 Dexie。

interface IFileBlob {
  id: string;
  file: Blob;
}

newState.fileResults 是这些数组:

export interface IFileResult {
  id: string;
  type: string;
}

那么这样的事情可能吗?

标签: angularasync-awaitrxjsangular2-observables

解决方案


您可以尝试使用“fromPromise”方法将 promise 对象(由 async 方法返回)转换为 observable。此外,使用“forkJoin”将所有可观察输出连接到单个可观察结果中,最后,将“map”替换为“switchMap”,将流替换为可观察累积结果。以下是可以帮助您的代表性代码:

function getCount(): Observable<number> {
  return of(10);
}

// This is your "getAsync" method
async function getNumberPromise(value: number) {
  return value;
}

// This is your inner 'newState.fileResults.forEach' loop
function getNumberObservables(entries: number[]): Observable<number[]> {
  return forkJoin(entries.map((value, index) => {
    return from(getNumberPromise(index));
  }));
}

// this is your 'this.ngRedux.select<ICommunicationState>('communication').pipe(map(...'
function getAllFiles(): Observable<number[]> {
  return getCount().pipe(switchMap(count => {
    const entries = new Array(count);
    return getNumberObservables(entries);
  }));
}

推荐阅读