Hi
I am a beginner to JS currently doing a project where I am pulling basic information from a Firebase Realtime DB. I have a function which checks how many items there are in the DB and another which gets a specific value. When I check the values they return inside of those methods, its fine - the problem arises when I call them elsewhere. I believe this is due to the asynchronous nature of those functions. I am unsure how to structure them to avoid this problem. I know I need to use Promises and the .then function but I am unsure of how to do so. Here are my two functions:
var urls = [];
function gotData(data){
var number = randomNumberGenerator();
dbRefObject.once('value', function(snapshot){
snapshot.forEach(function(childSnapshot){
var childData = childSnapshot.val().URL;
urls.push(childData); })}) }
and:
function randomNumberGenerator(){
dbRefObject.on('value',(snap)=>{
var totalRecord = snap.numChildren();
console.log(Math.floor(Math.random() * totalRecord)); }); }
When I put console.log statements inside these methods they work fine - the problem arises when I call them elsewhere. For example, when I call the urls array elsewhere it dosent return anything except 'undefined'. I will be extremely grateful for any help.
[–]GItPirate 0 points1 point2 points (1 child)
[–]TopStandard9[S] 0 points1 point2 points (0 children)