0

I have this code below to retrive data from firebase and turn into an array but whenever i call it it stops other functions from being called inside the code even tho I can perfectly call them in the console.

I've worked around this by using callback functions but I am at a point it just doesn't do anymore. How can make this part act like a normal function where I can call anytime without stopping the code.

function genList(){
    dataRef.on('value', data => {
    let arr = (data.val());
    let keys = Object.keys(arr);
    for (let i = 0; i < keys.length; i++) {
        let k = keys[i];
        let title = arr[k].title;
        let author = arr[k].author;
        let pages = arr[k].pages;
        let date = arr[k].date;
        let bookmark = arr[k].bookmark;
        let newList = new Object();
        newList.title = title;
        newList.author = author;
        newList.pages = pages;
        newList.date = date;
        newList.bookmark = bookmark;
        bookList.push(newList);
    }
})}

armn
  • 7
  • 1
  • I'm having a hard time understanding the problem. Can you clarify what you mean by "it stops other functions from being called inside the code"? Or better yet: can you add some `console.log` statements to the code that show the problem? – Frank van Puffelen May 09 '21 at 15:00
  • For example, if i add a console.log('blabla') just right after that, it doesn't work. But if i call it inside that function or use console, it works somehow – armn May 10 '21 at 06:15
  • It sounds like you're struggling with the fact that loading data from Firebase (and most modern cloud APIs) happens asynchronously. There is no way to change that though, so I recommend learning more about the callbacks you already mentioned, promises, and async/await. For more on these, see https://stackoverflow.com/a/34908497, https://stackoverflow.com/q/14220321 and https://stackoverflow.com/q/40688268 – Frank van Puffelen May 10 '21 at 14:25

0 Answers0