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)
问题是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)
| 归档时间: |
|
| 查看次数: |
559 次 |
| 最近记录: |