I have a function that either gets pictures from Firebase or locally saved pictures. For that I use promises. If there is no picture in Firebase to get, it should return the name of the error. This is the function:
function getPic(index){
let pic = document.createElement("img");
let errorName;
if(tempPhotos[index] == undefined){
storageRefPhotos.listAll().then(res=>{
res.items[index].getDownloadURL().then(url=>{
pic.src = url;
pic.classList.add("horizontal");
})}).catch(error => {
console.log("The function found an "+ error.name);
return error.name;
});
tempPhotos[index] = pic;
console.log("Got it from Firebase");
return pic;
}
else{
console.log("Got it locally");
return tempPhotos[index];
}
}
The line console.log("The function found an "+ error.name);
is executed as intended. However, in the following code, the else statement is always executed, even if the above line was executed.
const nextPic = getPic(currentPhoto+1);
if(nextPic.name==="TypeError"){
console.log("Executing the if");
console.log("The EventListener found a "+nextPic.name);
}
else{
console.log("Executing the else");
gallery.replaceChild(nextPic, arrow_left.nextElementSibling);
currentPhoto++;
}
The idea behind this is to create a slideshow of pictures. When there are no more pictures, it should start at the beginning. The code right above this text is part of an EventListener.
Thanks a lot!
EDIT:
I have revised my function to this:
function getPic(index){
let pic = document.createElement("img");
if(tempPhotos[index] == undefined){
storageRefPhotos.listAll().then(res=>{
res.items[index].getDownloadURL().then(url=>{
pic.src = url;
pic.classList.add("horizontal");
tempPhotos[index] = pic;
cl("Got it from Firebase");
return pic;
})
}).catch(error => {
console.log("The function found an "+ error.name);
return error.name;
});
}
else{
cl("Got it locally");
return tempPhotos[index];
}
}
Now, it always returns undefinded. I do not understand why. Additionally I have changed nextPic.name to nextPic.