1

I am trying to assign the download url to a variable but it's not applying it. The variable is outside the function so not sure where I am going wrong. I essentially want the download url string so I could use it for reference.

var img_path;
var upload_path;
if (img.length != 0){
                var imageFile = img[0];
                var imageName = imageFile.name;

              
                img_path = ‘/some-path/’ + imageName;
                //upload image
                let storageRef = firebase.storage().ref(img_path);
                storageRef.put(imageFile).then((savedPicture) => {

                storageRef.getDownloadURL().then(function(downloadURL) {
                  console.log('File available at', downloadURL);
                  upload_path = downloadURL;
                });

    });
//returns undefined
console.log(upload_path);
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
just4code
  • 27
  • 1
  • 5

1 Answers1

0

Determining the download URL is an asynchronous operation.

By the time your console.log(upload_path) runs, the upload_path = downloadURL hasn't run yet. You can most easily verify this by putting breakpoints on those lines and running in a debugger, or by checking the order of your logging output.

Any code that needs the download URL needs to be inside the callback that is called when that URL is available, or be called from there.

So the simplest fix it to move the code that needs the download URL into the callback.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807