У меня есть функция, которая получает изображения из Firebase или локально сохраненные изображения. Для этого я использую обещания. Если в Firebase нет изображения, которое нужно получить, оно должно вернуть имя ошибки. Это функция:
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];
}
}
Строка console.log("The function found an "+ error.name);
выполняется в соответствии с назначением. Однако в следующем коде оператор else всегда выполняется, даже если была выполнена вышеуказанная строка.
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++;
}
Идея, стоящая за этим, заключается в создании слайд-шоу изображений. Когда больше нет картинок, оно должно начинаться с начала. Код прямо над этим текстом является частью EventListener.
Большое спасибо!
РЕДАКТИРОВАТЬ:
Я изменил свою функцию следующим образом:
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];
}
}
Теперь он всегда возвращается неопределенным. Я не понимаю почему. Кроме того, я изменил nextPi c .name на nextPi c.