繁体   English   中英

等到图像完成上传到触发代码

[英]Waiting until image finishes upload to fire code

我正在努力强制代码同步。 该代码旨在使用 vue 可组合上传图像,等待上传成功,然后将 url 从 firebase 存储到数据库中。 我能做的最好的是将代码获取到 function,但是在上传完成之前成功代码会触发(尽管我得到了 url)。

下面的代码不起作用,但我尝试尝试使用 then 回调将操作链接在一起,以强制它们以同步方式运行。 不工作。

VueComponent.vue

const newImage = async () => {
      if (image.value) {
        await uploadImage(image.value);
      } else return null;
    };

    const handleSubmit = async () => {
     
      try {
      
        const colRef = collection(db, "collection");

        newImage()
          .then(() => {
            addDoc(colRef, {
              content: content.value
            });
          })
          .then(() => {
            //code to run only on success
              });
          });
       
      } catch (error) {
       
      }
    };

useStorage.js 可组合

import { ref } from "vue";
import { projectStorage } from "../firebase/config";
import {
  uploadBytesResumable,
  getDownloadURL,
  ref as storageRef,
} from "@firebase/storage";

const useStorage = () => {
  const error = ref(null);
  const url = ref(null);
  const filePath = ref(null);

  const uploadImage = async (file) => {
    filePath.value = `${file.name}`;

    const storageReference = storageRef(projectStorage, 
 filePath.value);

  //<--I want this to be synchronous, but it isn't.
    const uploadTask = uploadBytesResumable(storageReference, 
 file);

    uploadTask.on(
      "state_changed",
      (snapshot) => {
        const progress =
          (snapshot.bytesTransferred / snapshot.totalBytes) * 
 100;
        console.log("Upload is " + progress + "% done");
      },
      (err) => {
       
  
      },
      () => {
    getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) 
     => 
        {console.log("File available at", downloadURL);
      });
      }
    );
    
  };


  return { url, filePath, error, uploadImage };
};

export default useStorage;

您的uploadImage不会等待上传完成,这就是为什么addDoc比您希望的更早发生的原因。

const uploadImage = async (file) => {
  filePath.value = `${file.name}`;

  const storageReference = storageRef(projectStorage, 
filePath.value);

  const uploadTask = uploadBytesResumable(storageReference, 
file);

  await uploadTask; // 👈 Wait for the upload to finish

  const downloadURL = getDownloadURL(uploadTask.snapshot.ref)

  return downloadURL;
}

现在你可以调用它:

newImage()
  .then((downloadURL) => {
    addDoc(colRef, {
      content: content.value
    });
  })

或者,通过再次使用await

const downloadURL = await newImage();
addDoc(colRef, {
  content: content.value
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM