This method stores JSON objects retrieved from a firebase database to array scores.
function loadScoresToArray(){
databaseRef.orderByChild("Score").on("child_added", function (snap) {
scores.push(snap.val());
});
}
Run the above method and print content of scores
loadScoresToArray();
console.log(scores);
console.log(scores[0]);
output
As seen here, objects have correctly been added to scores.
But I can't retrieve them using index.
Reading similar questions like this I think this might be because when console.log(scores[0]);
is called, the array is still empty. It has not been populated yet. This is just my guess.
How do I solve this? Is there a way to create a delay until the array is populated?
But I can't retrieve them using index.
That's because you're performing an asynchronous operation. Instead of waiting for the response
, the execution continues immediately and the statement after the request call is execute.
How do I solve this? Is there a way to create a delay until the array is populated?
No, don't use a delay. You can use a callback
function.
function loadScoresToArray(callback){
databaseRef.orderByChild("Score").on("child_added", function (snap) {
scores.push(snap.val());
callback(scores);
});
}
loadScoresToArray(function(scores){
console.log(scores[0]);
});
Another solution is to use Promise
constructor in order to perform an asynchronous operation.
function loadScoresToArray(){
return new Promise(function(resolve, reject){
databaseRef.orderByChild("Score").on("child_added", function (snap){
scores.push(snap.val());
resolve(scores);
});
});
}
loadScoresToArray().then(function(scores){
console.log(scores[0]);
});
Here are possible approaches in order to solve your problem.
ES2017+
)ES2015+
)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With