itwabi
itwabi

Reputation: 145

Unable to access javascript array, and loop not working

Now i know that there's a possibility that my question has a duplicate. But even so, I'd appreciate it if you directed me to the right answer if possible.

Am kinda new to new to javascript and my problem is that I am unable to loop through an array.

so here's my script

 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);
});

all am trying to do is get a list of image urls from firebase storage and store them in an array and then use a for loop to display each of them to the html page. Now, when i log console.log(links[1]) i get undefined, and the for loop does not run altogether.

Any with any ideas, please help out. regards.

Upvotes: 0

Views: 62

Answers (2)

chingcm
chingcm

Reputation: 121

That is because you are pushing url to the array in the promise function itemRef.getDownloadURL() but calling console.log(links) out of the promise. console.log may run before you push url to the array.

Here is a way to modify your code:

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

However, you may need to do research on handling promise in loops so you get links with all URLs (e.g. Promise.all(), await/async)

Upvotes: 1

Taliane Tchissambou
Taliane Tchissambou

Reputation: 21

getDowloadUrl seems to be an async function so when you call log, links is empty because you did not get any answer yet.

Upvotes: 0

Related Questions