I am giving my first steps with Firebase Storage Web and confess that Javascript is not my speciality either.
I have a web page (PHP) with a list of people names and I want to show their repective photo next to the name. The images are saved in a Firebase Storage folder.
Here is a simple example of the html (generated with PHP):
<div id="people_list">
<div class="list_row">
<div class="photo">
<img id="photo1" src="images/stdphoto.png" width="50" height="50">
</div>
<div class="name">
People Name 1
</div>
</div>
<div class="list_row">
<div class="photo">
<img id="photo2" src="images/stdphoto.png" width="50" height="50">
</div>
<div class="name">
People Name 2
</div>
</div>
</div>
I already added the Firebase API following the instructions in this page https://firebase.google.com/docs/web/setup and initialize it like this:
firebase.initializeApp(config);
firebase.auth().signInAnonymously(); // Ignoring security for now
And here is my code to load ONE photo. It works perfectly!
var storage = firebase.storage();
var refPath = storage.ref('photos/johnnydepp.jpg');
refPath.getDownloadURL().then(function(url) {
document.getElementById('photo1').src = url;
}).catch(function(error) {
console.log(error);
});
But now I am trying to load all the images in the page, so I created an Javascript array variable with the file names (loaded with PHP) an did like this:
var photos = ["johnnydepp", "jimcarrey", "emmawatson"];
var photoId = 0;
var refPath = null;
var storage = firebase.storage();
for (var i = 0; i <= photos.length - 1; i++) {
photoId = i + 1;
refPath = storage.ref('photos/' + photos[i] + '.jpg');
refPath.getDownloadURL().then(function(url) {
document.getElementById('photo' + photoId).src = url;
}).catch(function(error) {
console.log(error);
});
}
I do not know why, but only the last photo in the list is being loaded. There are no errors in the Javascript console.
Please, do you know what I am doing wrong? Thanks!
EDIT (my solution):
const promises = [];
photos.forEach(val => {
const promise = firebase.storage()
.ref('photos/' + val + '.jpg')
.getDownloadURL()
.catch(err => {
console.log('error', err);
return "";
})
.then(fileUrl => {
return fileUrl;
});
promises.push(promise);
});
Promise.all(promises)
.catch(err => {
console.log('error', err);
})
.then(urls => {
for (var i = 0; i <= urls.length - 1; i++) {
if (urls[i] != '') {
document.getElementById('photo' + (i + 1)).src = urls[i];
}
}
});