Home > other >  Waiting until image finishes upload to fire code
Waiting until image finishes upload to fire code

Time:12-19

I am struggling to force code to be synchronous. The code is intended to upload an image using a vue composable, wait for the upload to succeed, then store the url from firebase storage into a database. The best I can do is get the code to function, but the success code fires before the upload is complete (though I get the url).

The code below does not work, but it's my attempt to try to chain the actions together using then callbacks to force them to behave in a synchronous manner. Not working.

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 composable

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;

CodePudding user response:

Your uploadImage doesn't wait for the upload to complete, so that's why the addDoc happens earlier than you want it to.

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

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

  const uploadTask = uploadBytesResumable(storageReference, 
file);

  await uploadTask; //            
  • Related