【发布时间】:2020-08-13 14:54:12
【问题描述】:
我有一个函数可以从 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];
}
}
现在,它总是返回未定义。我不理解为什么。此外,我已将 nextPic.name 更改为 nextPic。
【问题讨论】:
-
超级经典的异步题。
const nextPic = getPic(currentPhoto+1)不会返回您期望的值。就此而言,它根本不返回值。 -
为什么
nextPic.name==="TypeError",你已经返回error.name?应该是nextPic==="TypeError"
标签: javascript promise try-catch firebase-storage