Show a modal after images are uploaded with JS and Firebase

牧云@^-^@ 提交于 2020-06-29 07:02:58

问题


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 ?


回答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);
});


来源:https://stackoverflow.com/questions/60236053/show-a-modal-after-images-are-uploaded-with-js-and-firebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!