I am trying to get this piece of code to work and it seems to be running out of order. I noticed this in the console logs.
<script>
var wrapper = document.getElementById("myHTMLWrapper");
var myHTML = '';
var databaseRef = firebase.database().ref('items/');
databaseRef.once('value', function(snapshot)
{
snapshot.forEach(function(childSnapshot)
{
var childKey = childSnapshot.key;
var childData = childSnapshot.val();
myHTML += '<div class="card">';
myHTML += '<div class="card-body">';
var urlimage = '';
storageRef.child('images/'+ childData.id +'.jpg').getDownloadURL().then(function(url){
urlimage = url;
console.log(urlimage);
});
console.log('url outside of function is: '+urlimage);
myHTML += '<img src="'+ urlimage +'" class="img-thumbnail" height="">';
console.log('images/'+ childData.id +'.jpg');
myHTML += '<h4>'+ childData.sku + ' - ' + childData.name +'</h4>';
myHTML += '</div>';
myHTML += '</div>';
});
wrapper.innerHTML = myHTML;
});
</script>
It seems that the code is running console.log('url outside of function is: '+urlimage); before it runs console.log(urlimage);
I am not too familiar with Javascript yet and I hope I can get some help with this one.
Thanks!!!
storageRef.child('images/'+ childData.id +'.jpg').getDownloadURL().then(function(url){
urlimage = url;
console.log(urlimage);
});
The piece of code above from the code you provided actually uses Promises. You usually use promises when dealing with asynchronous data, for example, data from a server. While that piece of code is processing, other lines of code are being executed, thereby leading to what you are observing. The behavior of asynchronous code cannot be usually predicted.
To use urlimage you can do something like this.
storageRef.child('images/'+ childData.id +'.jpg').getDownloadURL().then(function(url){
myHTML += '<img src="'+ url +'" class="img-thumbnail" height="">';
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With