Show A Modal After Images Are Uploaded With Js And Firebase
Solution 1:
Both uploading data and getting a download URL are asynchronous operations. While the call to the server is going on, the rest of your code continues to run. Then when the server has returned data, your callback gets called.
This is easiest to understand if you place some logging statements:
console.log("Starting upload...");
imgRef1.put(file1).then(function(snapshot) {
console.log('Uploaded a blob or file. Getting download URL...');
snapshot.ref.getDownloadURL().then(function(downloadURL) {
console.log("File available at", downloadURL);
imgAns1 = downloadURL;
});
console.log("Started getting download URL");
}).catch(error => {
console.error("Error occurred: "+error);
});
console.log("Started upload");
If you run this code, the output will be:
Starting upload...
Started upload
Uploaded a blob or file. Getting download URL...
Started getting download URL
File available at...
So the code doesn't execute in the same order as it exists in your file. Instead the callbacks get called later, after the calls to the server are complete. Because of this any code that needs the data from the server needs to be inside the callback function, or be called from there.
Most likely you're calling document.getElementById("imgSelectAns1").src = imgAns1
from somewhere in your code, when imgAns1 = downloadURL
hasn't been called yet.
The fix is to move that code into the callback:
imgRef1.put(file1).then(function(snapshot) {
snapshot.ref.getDownloadURL().then(function(downloadURL) {
document.getElementById("imgSelectAns1").src = downloadURL;
});
}).catch(error => {
console.error("Error occurred: "+error);
});
Post a Comment for "Show A Modal After Images Are Uploaded With Js And Firebase"