等待图像完成上传以触发代码

Waiting until image finishes upload to fire code

我正在努力强制代码同步。该代码旨在使用 vue 可组合项上传图像,等待上传成功,然后将 url 从 firebase 存储存储到数据库中。我能做的最好的就是让代码运行,但是成功代码在上传完成之前触发(尽管我得到 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
});