jeudi 4 août 2016

Javascript - How to pull data from Google Firebase randomly?

I'd like all my Firebase content to load randomly every time you refresh, but I can't seem to get all my Firebase data into a dictionary where I can randomize them.

I have a global array and I'm trying to push my files in there and then iterate through them. But Javascript thinks the array is empty because the timing is off.

var randomStore = new Array;

function homeSetup() {
    if(ref.toString() == featuredRef.toString()){
        addFeaturedImages();
    }
    console.log('randomStore length is ' + randomStore.length);
}

function addFeaturedImages(){
    featuredRef.on("child_added", function(snapshot) {
        var doc = {
            // 'name': snapshot.key, //name is the id
            'artist': snapshot.val().artist,
            'author': snapshot.val().author,
            'projectTitle': snapshot.val().projectTitle,
            'text': snapshot.val().text
        };
        randomStore.push(doc);
        console.log('randomStore length HERE is ' + randomStore.length);
    });
}

Considering how the code is typed, I would assume that the 'randomStore length HERE is' log would be typed first, but instead I get this:

randomStore length is 0
randomStore length HERE is 1
randomStore length HERE is 2
randomStore length HERE is 3

If I got my data into a different array, then I could manipulate it to sort randomly and stuff like that, but I can't seem to get it in there properly.




Aucun commentaire:

Enregistrer un commentaire