正在等待,直到图像完成上载到激发代码



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

最新更新