Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can't access object inside array even though it exists [duplicate]

Tags:

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

enter image description here

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?

like image 789
Enzio Avatar asked Jan 03 '18 07:01

Enzio


1 Answers

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.

  • Promises with async/await (ES2017+)
  • Callbacks
  • Promises with then() (ES2015+)
like image 142
Mihai Alexandru-Ionut Avatar answered Sep 20 '22 12:09

Mihai Alexandru-Ionut