The issue lies in the timing of when the callback function is triggered in relation to the console log statement for myArr
. The callback function, which modifies myArr
, has not been executed by the time the "doesn't work" console log is called.
To address this issue, let's make a few adjustments to your code:
var myArr = [];
function show_fb() {
var firebase = new Firebase('https://scorching-fire-6816.firebaseio.com/');
firebase.on('child_added', on_post_added);
console.log(myArr);
return myArr;
};
function on_post_added(snapshot) {
var newPost = snapshot.val();
myArr.push(newPost.user);
console.log(myArr);
}
By rearranging your code like this, it should become clearer what exactly is happening.
- You set up a listener for
child_added
, triggering the on_post_added
function for each new post added to Firebase
- This action involves communication with the server, which can introduce delays
- While waiting for the server response, the JavaScript execution continues and...
- Logs an empty array at this point
- The function then returns the empty array
- Eventually, the server responds and your callback function is invoked
- Allowing you to add the new value to the array without any issues
- Logging the array now shows the expected values
Working with asynchronous operations and callbacks like this might take some getting used to, especially when dealing with technologies like Firebase or AJAX. Consider breaking down callback logic into separate functions for better clarity.
In Firebase, remember that child_added
event triggers whenever a child is added, even after initially registering the callback. Subsequent additions will still invoke the callback, but the code in steps 4 and 5 will have already executed by then.
To ensure proper handling of new data additions, place any post-processing actions within your callback function:
var myArr = [];
function show_fb() {
var firebase = new Firebase('https://scorching-fire-6816.firebaseio.com/');
firebase.on('child_added', on_post_added);
};
function on_post_added(snapshot) {
var newPost = snapshot.val();
myArr.push(newPost.user);
console.log(myArr);
// perform additional tasks related to new posts here
}