Reputation: 259
I have an array customers
declared outside of firebase ref.once()
function.
var customers = [];
I am changing the value of the array within ref.once()
and trying to access the modified value out of ref.once()
. But it returns the initial value []
.
Here is my code
var customers = [];
var nameRef = new Firebase(FBURL+'/customerNames/');
nameRef.once("value",function(snap){
customers.push("test");
});
console.log(customers); // returns []
Upvotes: 2
Views: 600
Reputation: 27506
The problem is that the once
callback is executed asynchronously and that the log statement is actually called before customers.push("test");
. Try the following code to see the order in which the code is executed:
var customers = [];
var nameRef = new Firebase(FBURL+'/customerNames/');
nameRef.once("value",function(snap){
customers.push("test");
console.log("Inside of callback: " + customers); // returns [test]
// At this point, you can call another function that uses the new value.
// For example:
countCustomers();
});
console.log("Outside of callback: " + customers); // returns []
function countCustomers() {
console.log("Number of customers: " + customers.length);
}
Upvotes: 5