【问题标题】:Firebase - how to await getDownloadURLFirebase - 如何等待 getDownloadURL
【发布时间】:2021-02-15 01:06:40
【问题描述】:

我有一个函数可以正确地从文档中检索数据。但是,一张图片的 URL 已经是它的字段。另一个图像只有一个 Firebase 图像参考。在继续执行另一个功能之前,我需要等到下载 URL 被获取。我在下面尝试过,但运气不佳,我也不完全确定我是否将async 卡在了正确的位置。

getPhoto(user_id: string) {
   this._subscription = this._activatedRoute.params.pipe(
   switchMap(params => {
    return this.service.getPhoto(params);
  })
  ).subscribe(async(result) =>  {
    const imageOne = result.imageOne;

    // Need to await the download URL here
    const imageTwo = this.blah(result.imageTwoRef)

    this.otherFunction(imageOne, imageTwo)
  
  });
 }


blah(reference){
  var storage = firebase.storage();
  var imageTwo = reference;
  var imagePathRef = storage.ref().child(imageTwo);  
  imagePathRef.getDownloadURL().then((url) => {
    return url;
  }); 
}

【问题讨论】:

    标签: javascript angular firebase firebase-storage


    【解决方案1】:

    使用 async 关键字仅适用于函数,这样做会返回一个 Promise。所以在那种情况下你的用法是正确的。
    您只能在异步函数中和 Promise 调用旁边使用 await。它将停止执行,直到您的承诺得到解决。
    我想你差不多完成了。试试这样,让我知道:

    getPhoto(user_id: string) {
       this._subscription = this._activatedRoute.params.pipe(
       switchMap(params => {
        return this.service.getPhoto(params);
      })
      ).subscribe(async(result) =>  {
        const imageOne = result.imageOne;
    
        // Need to await the download URL here
        const imageTwo = await this.blah(result.imageTwoRef)
    
        this.otherFunction(imageOne, imageTwo);
      
      });
     }
    
    
    async blah(reference){
      var storage = firebase.storage();
      var imageTwo = reference;
      var imagePathRef = storage.ref().child(imageTwo);  
      const url = await imagePathRef.getDownloadURL();
      return url;
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-04
      • 2016-12-16
      • 1970-01-01
      • 1970-01-01
      • 2021-04-06
      • 2020-05-13
      • 2020-06-28
      相关资源
      最近更新 更多