0
我试图在数组中保存快照属性,但由于某种原因,当我将数据存储在查询中时(例如使用on
或child_added
并使用foreach
运行数据),数据显示在循环内部并且查询,但在此之外它的价值是不确定的,我尝试了对象,但只救出了最后一个值,这个问题怎么解决?如何使用Firebase和JavaScript将快照保存到数组中?
这里有一个代码片段:
var array=[];
var ref= firebase.database().ref().child('messages');
ref.orderByChild("fecha").on('value',function(snapshot){
snapshot.forEach(function(snap){
//test array
array[0] = snap.val().text;
console.log(array[0]);//show the data
});
});
//but out of the loop
console.log(array[0]);//Return undefined
'on'是异步的,它的回调不会在你的代码片段中最后一次'console.log'调用之后触发。 – cartant
[在函数中处理异步调用(Firebase)]的可能重复](http://stackoverflow.com/questions/11636731/handling-asynchronous-calls-firebase-in-functions) – cartant