数组没有在firebase中更新一次()

Sha*_*ico 2 javascript arrays angularjs firebase

我有一个customers在firebase ref.once()函数之外声明的数组.

var customers = [];

我正在更改数组的值ref.once()并尝试访问修改后的值ref.once().但它返回初始值[].

这是我的代码

  var customers = [];
  var nameRef = new Firebase(FBURL+'/customerNames/');
  nameRef.once("value",function(snap){
      customers.push("test");
  });
  console.log(customers); // returns []
Run Code Online (Sandbox Code Playgroud)

sch*_*sch 5

问题是once回调是异步执行的,之前实际调用了log语句customers.push("test");.请尝试以下代码以查看代码的执行顺序:

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);
}
Run Code Online (Sandbox Code Playgroud)

  • 在执行回调之前,该值不会更改.因此,您应该在回调中调用需要修改值的相应代码.你可能应该更好地解释你需要什么,和/或发布需要修改值的颂歌,以获得更具体的解释. (2认同)