'wait for function execution before executing next instruction
I'm trying to upload images to firebase and get the download Url and save the url in the firestore in the database. The code was working until I modified it to handle multiple images. To handle multiple images I have implemented promises.
The functions uploadFiles() and addRecord() works completely fine seperately. But I want to run the functions together in onSubmit() function. The problem I'm facing is that addRecord() runs before the uploadFiles() completes its execution.
I have tried promises and async await to control the flow but unsuccessfull. I'm new to handling promises and stuck at it.
here's the uploadFiles code
const uploadFiles = (data) => {
const promises = [];
data.images.map((file) => {
console.log("loop");
const sotrageRef = ref(storage, `files/${file.name}`);
const uploadTask = uploadBytesResumable(sotrageRef, file);
promises.push(uploadTask);
uploadTask.on(
"state_changed",
(snapshot) => {
const prog = Math.round(
(snapshot.bytesTransferred / snapshot.totalBytes) * 100
);
setProgress(prog);
},
(error) => console.log(error),
async () => {
await getDownloadURL(uploadTask.snapshot.ref).then((downloadURLs) => {
setUrls((prevState) => [...prevState, downloadURLs]);
console.log("File available at", downloadURLs);
});
}
);
});
Promise.all(promises)
.then(() => alert("All images uploaded"))
.catch((err) => console.log(err));
};
here's the onSubmit function
const onSubmit = async (data) => {
console.log("before upload");
await uploadFiles(data);
console.log("after upload");
console.log(urls);
await addRecord({
title: data.title,
eventType: data.eventType,
date: data.date,
venue: data.venue,
description: data.description,
details: data.details,
images: urls,
link: data.link,
scheduleType: data.scheduleType,
});
};
The upload files sets the state of the urls to the image urls from the firebase storage. I have console logged messages before and after the uploadFiles. The console.log(urls)
returns an empty array after the uploadFiles is completed, but the values are being populated with urls after the addRecord
is being executed. This is resulting the firestore record to be an empty array for images.
Here's a screenshot of the console
Is anything wrong with the way I'm handling promises and async await.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|