I’m trying to redirect to another page after all the file are done uploading to firebase storage. It keep executing the redirect code before finishing the uploads. Can’t figure out how to execute one after the other. This is a js scripts running on client side of the website.
if (file[0].files[0]) { uploadFile(file[0]); } if (file[1].files[0]) { uploadFile(file[1]); } if (file[2].files[0]) { uploadFile(file[2]); } console.log("All files finished"); window.location.href = "success.html"; function uploadFile(file) { var task = storage.ref("arts/" + emailValue + Date.now()).put(file.files[0]); task.on('state_changed', function progess(snapshot) { var progressValue = (snapshot.bytesTransferred / snapshot.totalBytes) * 100; console.log(progressValue); }, function error(err) { console.log(err); }, function completed() { console.log('file upload success'); task.snapshot.ref.getDownloadURL().then(function(downloadURL) { imgUrl = downloadURL; storeDetails(); }); } ); } function storeDetails() { db.collection("participants").doc(emailValue + Date.now()).set({ email: emailValue, url: imgUrl.toString(), }) .then(function() { console.log("Document successfully written!"); }) .catch(function(error) { console.error("Error writing document: ", error); }) }
Advertisement
Answer
Returned a promise from the uploadFile and storeDetail functions then made the submit function async and await for uploadFile function call, for complete.
submitButton.addEventListener("click", async function () { if (file[0].files[0]) { await uploadFile(file[0], progressBar[0]); } if (file[1].files[0]) { await uploadFile(file[1], progressBar[1]); } if (file[2].files[0]) { await uploadFile(file[2], progressBar[2]); } console.log("All files finished"); } }) function storeDetails() { return new Promise((resolve, _reject) => { db.collection("participants").doc(emailValue + Date.now()).set({ email: emailValue, url: imgUrl.toString(), }) .then(function () { console.log("Document successfully written!"); resolve("success") }) .catch(function (error) { console.error("Error writing document: ", error); }) }); } function uploadFile(file, progressBar) { return new Promise((resolve, _reject) => { var task = storage.ref("arts/" + emailValue + Date.now()).put(file.files[0]); task.on('state_changed', function progess(snapshot) { var progressValue = (snapshot.bytesTransferred / snapshot.totalBytes) * 100; console.log(progressValue); progressBar.style.width = progressValue + '%'; }, function error(err) { console.log(err); }, function completed() { console.log('file upload success'); task.snapshot.ref.getDownloadURL().then(async function (downloadURL) { imgUrl = downloadURL; await storeDetails(); resolve("Completed"); }); } ); }); }