代码之家  ›  专栏  ›  技术社区  ›  Diskdrive

在返回函数之前,如何等待所有订阅运行完毕?

  •  -1
  • Diskdrive  · 技术社区  · 7 年前

    我想在firebase存储中显示一组图像。我的服务中有一个功能,我想一次下载所有的URL。我不确定如何编写它,使photoSrcs只在所有订阅函数运行后才退出。

    我已经粘贴了下面的代码,但是很明显,photoSrcs将是空的。

    loadPhotoUrls(photos : Photo[]) : any
      {
        const photoSrcs = {};
    
        photos.forEach(async (photo, index) => {
          const fileRef = this.storage.ref('photo.fileLocation');
    
          fileRef.getDownloadURL().subscribe(url => {
            photoSrcs[photo.id] = url;
          });
        });
    
        return photoSrcs;
      }
    
    1 回复  |  直到 7 年前
        1
  •  3
  •   Oles Savluk    7 年前

    使用 forkJoin operator 要等待一系列的可观测数据,比如:

    const { forkJoin, of } = rxjs; // = require("rxjs")
    
    // simulate API call
    const fetchFromApi = id => of(`result: ${id}`);
    
    const ids = [1, 2, 3, 4, 5];
    const requests = ids.map(fetchFromApi);
    forkJoin(requests)
      .subscribe(e => console.log(e))
    <script src="https://unpkg.com/rxjs@6.3.3/bundles/rxjs.umd.min.js"></script>