我正在努力強制代碼同步。該代碼旨在使用 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;
uj5u.com熱心網友回復:
您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
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/385865.html
