Dharmaraj
Dharmaraj

Reputation: 50930

For loop not working after Firebase Database Read in JavaScript

I have many articles in my firebase realtime database and I have named their node in a series of numbers.

I want to retrieve them using a for-loop. Before that I check how many articles are available and then run the FOR loop accordingly. But when I receive number of articles available the program stops and the for loop won't run.

Here is my code:

let numOfArticlesAvailable;

const numOfArticlesRef = firebase.database().ref('/articles/available-count');
numOfArticlesRef.on('value', function (snapshot) {
    console.log('Articles Available: ' + snapshot.val());
    numOfArticlesAvailable = snapshot.val();
    console.log(numOfArticlesAvailable);
})

for (let index = numOfArticlesAvailable; index >= 1; index--) {
    const articlesRef = firebase.database().ref(`/articles/${index}`);
    console.log(articlesRef);
    articlesRef.on('value', function (snapshot) {
        const title = snapshot.val().title;
        const content = snapshot.val().content;
        const timestamp = snapshot.val().timestamp;

        console.log(`${title} has contents "${content}" and timestamp ${timestamp}`)
    })
}

The code log the correct value of articles available but the for-loop just won't start.

Upvotes: 0

Views: 282

Answers (1)

Lazar Nikolic
Lazar Nikolic

Reputation: 4404

Your for loop is not starting because numOfArticlesRef.on('value', function (snapshot) { is async function. This means that in the moment you for loop starts, value of numOfArticlesRef is either undefined or 0. or something like that. Try to do this:

let numOfArticlesAvailable;

const numOfArticlesRef = firebase.database().ref('/articles/available-count');
numOfArticlesRef.on('value', function (snapshot) {
    console.log('Articles Available: ' + snapshot.val());
    numOfArticlesAvailable = snapshot.val();
    console.log(numOfArticlesAvailable);
for (let index = numOfArticlesAvailable; index >= 1; index--) {
    const articlesRef = firebase.database().ref(`/articles/${index}`);
    console.log(articlesRef);
    articlesRef.on('value', function (snapshot) {
        const title = snapshot.val().title;
        const content = snapshot.val().content;
        const timestamp = snapshot.val().timestamp;

        console.log(`${title} has contents "${content}" and timestamp ${timestamp}`)
    })
}

})

Upvotes: 1

Related Questions