【问题标题】:Get url of multi images when upload them to Firebase Storage将多张图片上传到 Firebase 存储时获取它们的 url
【发布时间】:2020-11-19 09:25:19
【问题描述】:

您能帮我在将图片上传到 Firebase 时获取 URL 数组吗?

my imageUrl = [undefined, undefined] 上传 2 个 img 时

export const handleUploadProductPhoto = async (files) => {
  const imageUrl = await Promise.all(
    files.map((file) => {
      new Promise((resolve, reject) => {
        const uploadTask = firebase
          .storage()
          .ref()
          .child(`your/file/path/${file.name}`)
          .put(file);
        uploadTask.on(
          firebase.storage.TaskEvent.STATE_CHANGED,
          (snapshot) => {
            const progress =
              (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
            if (snapshot.state === firebase.storage.TaskState.RUNNING) {
              console.log(`Progress: ${progress}%`);
            }
          },
          (error) => console.log(error),
          () => {
            uploadTask.snapshot.ref
              .getDownloadURL()
              .then((url) => resolve(url));  //I have success here - two urls
          }
        );
      });
    })
  ).then((res) => console.log(res));
};

【问题讨论】:

  • 乍一看,代码看起来不错。所以你是说底部的console.log(res) 最终会记录[undefined, undefined]
  • 我在我的传奇中的 try/catch 块中调用 handleUploadProductPhoto 并得到 [undefined,undefined]。我是初中生,我是女孩)))))我可能对 Promise.all 有一些问题?
  • 我无法理解为什么 url s(我已经成功从 firebase 获取它们)不属于 Promise all result
  • 如果问题仅出现在handleUploadProductPhoto 之外,请编辑您的问题以显示问题出现的位置。如果您向我们展示重现问题的最少、完整的代码,然后准确指出哪一行给出了意外结果(因此我对是否是 console.log(res) 发表评论),我们很可能会提供帮助。
  • 是的,在底部我收到了 then((res) => console.log(res) [undefined, undefined]);

标签: javascript firebase web firebase-storage


【解决方案1】:

您的new Promise 上缺少return。所以应该是:

return new Promise((resolve, reject) => {
  ...

没有return,每个files.map((file) => { 什么都不返回(所以undefined),这就是Promise.all 然后传递给你的then

【讨论】:

  • 你是超级明星!!!它有效))))我的愚蠢错误))谢谢
  • 很高兴听到它。并没有什么愚蠢的。我也花了一段时间才发现它。 :)
猜你喜欢
  • 2018-02-26
  • 1970-01-01
  • 2020-04-14
  • 2016-12-24
  • 2020-04-01
相关资源
最近更新 更多