【发布时间】:2020-08-01 04:06:51
【问题描述】:
现在我知道我的问题有可能重复。但即便如此,如果可能的话,如果您将我引导到正确的答案,我将不胜感激。
我对 javascript 有点陌生,我的问题是我无法循环遍历数组。
这是我的脚本
var reference = firebase.storage().ref();
var listRef = reference.child('images');
var img = document.getElementById('productImageOne');
var img2 = document.getElementById('productImageTwo');
var img3 = document.getElementById('productImageThree');
var links = [];
// Find all the prefixes and items.
listRef.listAll().then(function(res) {
res.prefixes.forEach(function(folderRef) {
// All the prefixes under listRef.
// You may call listAll() recursively on them.
});
res.items.forEach(function(itemRef) {
// All the items under listRef.
var productRef1 = firebase.database().ref('Business/Products');
productRef1.on('value', function(snapshot) {
var products = snapshot.val();
products
const values = Object.values(products);
values.reverse();
for(const value of values){
//console.log(value["ShopName"])
if(value["ShopName"] === shop){
nombre = value["Name"];
console.log(itemRef.name.includes(value["Name"]));
if(itemRef.name.includes(nombre)){
itemRef.getDownloadURL().then(function(url) {
// `url` is the download URL for 'images/stars.jpg'
// This can be downloaded directly:
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function(event) {
var blob = xhr.response;
};
xhr.open('GET', url);
xhr.send();
console.log(url);
links.push(url); //this is my array i want to iterate.
}).catch(function(error) {
// Handle any errors
console.log(error);
});
//this prints the array showing its contents normally
console.log(links);
console.log(links[1]); //this gives undefined
//for loop doesn't even run to begin with.
for(const link of links){
console.log(link);
console.log("this is looping");
}
}
}
}
});
});
}).catch(function(error) {
// Uh-oh, an error occurred!
console.log(error);
});
我要做的就是从 firebase 存储中获取图像 url 列表并将它们存储在一个数组中,然后使用 for 循环将它们中的每一个显示到 html 页面。现在,当我登录 console.log(links[1]) 时,我得到了未定义,并且 for 循环没有完全运行。
任何有任何想法的人,请帮忙。问候。
【问题讨论】:
-
你必须先了解什么是承诺,然后在问这个问题之前学习如何使用异步,因为答案对你来说没有意义,而且只是复制粘贴而不是实际帮助你会更好。
-
酷,...让我继续努力。
标签: javascript firebase firebase-realtime-database firebase-storage