0

I want to store the download URL of an image as part of the post data, but am not able to do so, as the downloadURL is not stored in the imgURL variable. However, the downloadURL is able to print properly with console.log.

var postKey = firebase.database().ref('Posts/').push().key;

var imgURL = null;

uploadTask.snapshot.ref.getDownloadURL().then(function(downloadURL) {
    imgURL = downloadURL;
    console.log('File available at', downloadURL);
});

var updates = {};
var postData = {
    url: imgURL,
    caption: $("#imageCaption").val()
};

updates['/Posts/' + postKey] = postData;
firebase.database().ref().update(updates);
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) –  Jan 08 '19 at 18:05
  • 1
    You need to put everything starting from `var updates` *inside* the callback where you `console.log()`, or the rest of the code runs *before* you get back the download URL. Firebase is async, that's why you use callback functions in the first place. –  Jan 08 '19 at 18:06
  • That worked, thanks! I thought I had already attempted that. – Kevin Ferrandiz Jan 08 '19 at 18:38

0 Answers0