Javascript 数组未在firebase once()内更新
我在firebaseJavascript 数组未在firebase once()内更新,javascript,arrays,angularjs,firebase,Javascript,Arrays,Angularjs,Firebase,我在firebaseref.once()函数之外声明了一个数组customers var客户=[] 我正在更改ref.once()中数组的值,并尝试从ref.once()中访问修改后的值。但它返回初始值[] 这是我的密码 var customers = []; var nameRef = new Firebase(FBURL+'/customerNames/'); nameRef.once("value",function(snap){ customers.push("t
ref.once()函数之外声明了一个数组customers
var客户=[]代码>
我正在更改ref.once()
中数组的值,并尝试从ref.once()
中访问修改后的值。但它返回初始值[]
这是我的密码
var customers = [];
var nameRef = new Firebase(FBURL+'/customerNames/');
nameRef.once("value",function(snap){
customers.push("test");
});
console.log(customers); // returns []
问题在于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);
}
但是,我想在数组customers
中使用once()之外的推送值。如何实现?在执行回调之前,该值不会更改。因此,您应该在回调中调用需要修改值的适当代码。您可能应该更好地解释您需要什么,和/或发布需要修改值的ode,以获得更具体的解释。我如何知道回调已完成执行?这样我就可以调用另一个使用数组值的代码了?