Here I have 2 functions that will upload files to the firebase storage. So the process here is to upload the file and add that returned url to a array , and it is functioning as expected. But the problem here is if there were no file uploaded the,
return new Promise((resolve, reject) => {
if (type == "paragraph") {
resolve(paragraphUrl.push(""));
}
resolve("");
});
part executes before the previous file upload and add a value to the array. How can I fix this?
Upload Image function
let uploadImage = (reference, file, type, notDisabled) => {
if (notDisabled) {
if (type == "banner") {
file = banner[0];
} else if (type == "logo") {
file = logo[0];
} else if (type == "popup") {
file = popupImage[0];
}
return new Promise((resolve, reject) => {
let upload = reference.put(file).then((snapshot) => {
snapshot.ref.getDownloadURL().then((downloadURL) => {
if (type == "banner") data.bannerPath = downloadURL.toString();
else if (type == "logo") data.logo = downloadURL.toString();
else if (type == "popup") data.popupImage = downloadURL.toString();
else if (type == "paragraph") {
resolve(paragraphUrl.push(downloadURL));
}
resolve(downloadURL);
});
});
});
} else {
return new Promise((resolve, reject) => {
if (type == "paragraph") {
resolve(paragraphUrl.push(""));
}
resolve("");
});
}
};
function f1(){
Promise.all([
uploadImage(bannerRef, null, "banner", bannerAdded),
uploadImage(logoRef, null, "logo", logoAdded),
uploadImage(popupref, null, "popup", popUpAdded),
]).then(() => {
data.name = name;
data.url = url;
data.description = description;
if (document.getElementsByName("paragraphImageUpload").length != 0) {
for (const file of document.getElementsByName("paragraphImageUpload")) {
let fileName, image, paragraphRef, fileAvailable;
if ((file as HTMLInputElement).files.length != 0) {
fileName = (file as HTMLInputElement).files[0].name;
image = (file as HTMLInputElement).files[0];
paragraphRef = storageRef.child("projects/" + url + "/" + fileName);
fileAvailable = true;
} else {
fileAvailable = false;
}
Promise.all([
uploadImage(paragraphRef, image, "paragraph", fileAvailable),
]).then(() => {
paragraphData = paragraphData.map(
function (x, i) {
return {
Title: x.Title,
Paragraph: x.Paragraph,
Image: paragraphUrl[i],
};
}.bind(this)
);
data.ParagraphData = paragraphData;
console.log(data);
firebase.firestore().collection("projects").doc(url).set(data);
alert("done");
});
}
} else {
data.ParagraphData = paragraphData;
firebase.firestore().collection("projects").doc(url).set(data);
alert("done");
}
});
}