【问题标题】:Unable to access javascript array, and loop not working无法访问 javascript 数组,并且循环不起作用
【发布时间】: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


【解决方案1】:

那是因为你在 promise 函数 itemRef.getDownloadURL() 中将 url 推送到数组,但在 promise 之外调用了 console.log(links)console.log 可能会在您将 url 推送到数组之前运行。

这是修改代码的一种方法:

itemRef.getDownloadURL()
.then(function(url) {
  links.push(url)
})
.then(function() {
  console.log(links)
})
.catch(function (err) {
  console.log(err)
})

但是,您可能需要研究如何处理循环中的 Promise,以便获得带有所有 URL 的 links(例如 Promise.all()await/async

【讨论】:

  • 谢谢,....解决了我的问题。我一定会阅读 javascript 中的异步任务
【解决方案2】:

getDowloadUrl 似乎是一个异步函数,所以当你调用 log 时,链接是空的,因为你还没有得到任何答案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-15
    • 1970-01-01
    • 2020-12-01
    • 1970-01-01
    • 2011-10-14
    • 2021-05-13
    • 1970-01-01
    • 2019-10-14
    相关资源
    最近更新 更多