0

How to show a modal after images being uploaded to firebase storage.

   imgRef1.put(file1).then(function(snapshot) {
            console.log('Uploaded a blob or file!');
                snapshot.ref.getDownloadURL().then(function(downloadURL) {
                    console.log("File available at", downloadURL);
                    imgAns1 = downloadURL;
                });
   }).catch(error => {
        console.log("Error Occured");
   });;

I am uploading a file with the above code, and getting the image URL. And then I am assigning it to a imageview src in a modal.

 document.getElementById("imgSelectAns1").src = imgAns1;

But when modal opens up image won't load because it takes some time to upload this. How can I open the modal after the image is being successfully uploaded ?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • 1
    Where exactly are you doing `document.getElementById("imgSelectAns1").src = imgAns1;`? Can you show your entire code? Including the code for the modal window. We need to see the full code in order to be able to help you. – Renaud Tarnec Feb 15 '20 at 13:23

1 Answers1

0

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);
});
Community
  • 1
  • 1
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807