【发布时间】:2016-08-16 03:06:32
【问题描述】:
只是想由一些专家来运行它并了解他们的想法。我这样做的方式感觉有点老套。
这是我的代码:: 基本上我找到用户所属的组,然后搜索组。如您所见,我运行了一个 for 循环,该循环返回每个不同组的对象。一切正常,但问题是它似乎有很多查询,并且由于某种原因回调函数在代码执行完成之前运行。
var query = firebaseApp.database().ref().child('members').orderByChild('uid').equalTo(testUID);
query.once('value').then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
userObject = childSnapshot.val()
userGroups = userObject.groups.groupID
console.log("User Groups==")
console.log(userGroups)
pullGroupInfo(
function(){
console.log("###########@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
}
);
});
// end of get groups quer
});
function pullGroupInfo(callback) {
for(var i = 0; i < userGroups.length; i++) {
/* do some stuff */
var query = firebaseApp.database().ref().child('groups').orderByChild('id').equalTo(userGroups[i]);
query.once('value').then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
console.log("=")
console.log(childSnapshot.val())
groups.push(childSnapshot.val())
});
});
}
callback();
}
这是我的 json,以备不时之需:
{
"groups" : {
"-KO0C5FdTWisnc4i9xxM" : {
"id" : "jkdjsneind",
"members" : {
"General" : true,
"TechChat" : true
},
"name" : "joe",
"type" : "private"
},
"-KODDD0C5FdTWisnc4i9xxM" : {
"id" : "jkdjfbdkbfj",
"members" : {
"General" : true,
"TechChat" : true
},
"name" : "jack",
"type" : "private"
},
"-KODDD0C5FdTWisnc4i9xxMxx2" : {
"id" : "dfdsfds",
"members" : {
"General" : true,
"TechChat" : true
},
"name" : "bigcat",
"type" : "private"
},
"dicky" : "d",
"ggg" : "gg"
},
"members" : {
"-KO0C5FdTWisnc4i9xxM" : {
"ageRange" : "18-20",
"college" : "",
"dob" : "",
"firstname" : "joe",
"friends" : {
"UserID1" : true,
"UserID2" : true,
"UserID3" : true
},
"groups" : {
"groupID" : [ "jkdjfbdkbfj", "jkdjsneind" ]
},
"lastname" : "caraccio",
"name" : "joe",
"pendingFriends" : {
"UserID4" : true
},
"uid" : "6hOnKHBdkMWOaRFKiXyxLkU9lO33"
}
}
任何帮助都会很棒!
【问题讨论】:
-
codereview.stackexchange.com 是向 cmets 请求工作代码风格的更好地方。寻求帮助解决问题。
-
query.once()是异步的。您无需等待完成即可致电callback()。 -
啊,@Barmar。我会记住这一点。您如何建议我让它等待完成,它们是同步功能吗?你会建议如何解决它
标签: javascript json firebase firebase-realtime-database