I am currently working on a form that requires users to input data in order to generate a detailed city document. Additionally, users must upload multiple photos of the city as part of this process. Once the form is submitted, a new city document is created in firestore. Each photo is then uploaded to firebase storage and a new field called photosURLs
, containing all the URLs of the uploaded photos, is added to the city document.
Below is the code I have written:
async function addDocument() {
const docRef = await addDoc(collection(db, "cities"), {
name: "Tokyo",
country: "Japan"
});
return docRef
}
async function UploadMultiplePhotos(docRef) {
var photos = []
for (var i = 0; i < files.value.length; i++) { // files.values contains all the files objects
const file = files.value[i];
refStorageFunction(
storage,
"cities/" +
docRef.id +
"/" +
file.name
);
uploadBytes(storageRef, file).then((snapshot) => {
getDownloadURL(snapshot.ref).then((downloadURL) => {
photos.push(downloadURL)
});
});
}
return Promise.resolve(photos)
}
async function updateDocument(docRef, photos) {
await updateDoc(docRef, { photosURLs: photos });
}
function createCity() {
addDocument().then((docRef) => {
UploadMultiplePhotos(docRef).then((photos) => {
updateDocument(docRef, photos).then(() => {
router.push($CITY_PATH)
})
})
})
}
However, I am encountering an issue where the resulting photosURLs
field in the city document remains empty. It appears that my UploadMultiplePhotos
function does not properly wait for the photos
array to be fully populated.