2

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 []

1 Answer 1

5

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);
}
Sign up to request clarification or add additional context in comments.

3 Comments

But, i want to use the pushed values in array customers outside of once(). How it cane be achieved ?
The value won't change until the callback is executed. So you should call the appropriate code that needs the modified value from within the callback. You probably should explain better what you need, and/or post the ode that needs the modified value, to get a more specific explanation.
How can i know the callback has been completed executing? so that i can call another code that uses the array value?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.