Although there are numerous resources on Javascript promises for loading Firebase objects, I have struggled to store the data in an array.
The challenge: Despite setting up an array (productArray
below) to receive values from a Firebase snapshot, the array remains empty after exiting the forEach
loop.
database.js:
getProductList = function(){
let productArray =[];
loadFBData = function(){
firebase.initializeApp(config);
return firebase.database().ref().once("value", function(snapshot){
return snapshot.val();
});
}
Promise.all([loadFBData()]).then(function(snapshot) {
snapshot.forEach(function(product) {
productArray.push(product.val());
});
});
}
Question: I suspect I am mishandling Promise.all
, but I cannot figure out how (since I am new to asynchronous functions). Any guidance on successfully populating productArray
would be greatly appreciated.
Edit: Further explanation - it appears that snapshot
contains the correct Firebase data and the forEach
loop iterates through each item in snapshot
properly. However, productArray
remains empty outside of the Promise.all
block.
Update: I have tried implementing all the suggestions provided so far, yet the program does not pause long enough to build an array from the snapshot object. In the past, I have used Angularfire's $loaded
function, which effectively delayed the program execution. It is perplexing why a standard JS promise
does not work here. Should I consider using setTimeout
? Even attempting to combine alexmac's and Pointy's recommendations did not yield results:
getProductList = function(){
let productArray =[];
loadFBData = function(){
firebase.initializeApp(config);
return new Promise(resolve => {
firebase.database().ref().once('value')
.then(function(snapshot){
return resolve(function(snapshot){
productArray = Object.keys(snapshot).map((key, prod) => prod);
});
});
});
}
loadFBData();
}