【问题标题】:promise.all to use getDownloadURL() in firebasepromise.all 在 firebase 中使用 getDownloadURL()
【发布时间】:2020-04-24 14:47:22
【问题描述】:

我正在努力获取 Firebase 存储中的下载图片 URL。

我想用这段代码实现的是一张接一张地上传两张图片,并将图片的 URL 推送到数组中。

但是,我的代码不能作为异步正常工作。 Promise.all() 之后的结果假设返回带有 URL 的数组。 如果有人指导我解决此问题,我将不胜感激。

const handleUpload = () => {
    Promise.all([uploadImage(window1Image), uploadImage(window2Image)])
      .then((result) => {
        console.log(result);
      })
      .catch((err) => {
        console.log(err);
      });
  };

const uploadImage = (image) => {
    const uuid = Date.now() + uuidv4();
    const imageToServer = storage.ref(`images/${uuid}`).put(image);
    imageToServer.on(
      'state_changed',
      (snapshot) => {
        const progress = Math.round((snapshot.bytesTransferred / snapshot.totalBytes) * 100);
      },
      (error) => {
        console.log(error);
      },
      () => {
        storage
          .ref('images')
          .child(uuid)
          .getDownloadURL()
          .then((data) => data);
      },
    );
  };

【问题讨论】:

  • 可能是你没有设置Promise.all返回。
  • 我认为你需要从uploadImage函数返回imageToServer(Promise)

标签: javascript firebase asynchronous promise firebase-storage


【解决方案1】:

您应该使用UploadTaskthen() 方法,该方法“行为类似于Promise,并在上传完成时使用其快照数据进行解析”。

以下应该可以工作(未经测试):

  const handleUpload = () => {
    Promise.all([uploadImage(window1Image), uploadImage(window2Image)])
      .then(result => {
        console.log(result);
      })
      .catch(err => {
        console.log(err);
      });
  };

  const uploadImage = image => {
    const uuid = Date.now() + uuidv4();
    const imageToServer = storage.ref(`images/${uuid}`).put(image);
    return imageToServer.then(uploadTaskSnapshot => {
      return uploadTaskSnapshot.ref.getDownloadURL();
    });
  };

【讨论】:

  • 您好,感谢您的解决方案。你说的对。此代码完美运行!
猜你喜欢
  • 2022-01-04
  • 2021-04-06
  • 2020-05-13
  • 2021-02-15
  • 2021-01-04
  • 1970-01-01
  • 1970-01-01
  • 2022-06-18
  • 1970-01-01
相关资源
最近更新 更多