I have one node named as group_chat and another one named as users . The node group_chat contains the children which contains message, time and sender_id. Whereas the node users contains the details of users. When I retrieve chats from group_chat node, I also want to display the information of each sender. On using this code
rootChat.on("child_added", function (snapshot) {
if(snapshot.val().sender_id == logged_in_user_id) {
// Message by You
// Print snapshot.val().message
}
else{
const refUser = "/users/"+snapshot.val().sender_id;
const rootUser = database.ref(refUser);
rootUser.once("value", function(snap) {
// Print snap.val().name
// Display snap.val().picture
// Print snapshot.val().message
});
}
});
The problem is, when the code goes in else condition where it's the message of the other user, it retrieves the information of the user by going through the specific node. But while doing it, it automatically goes to next child while going through the user detail of first child which automatically spoils the arrangement of messages showing latest message in the middle, middle one in end and so on. If I have 4 children named as -child1, -child2, -child3 and -child4 in node group_chat , while checking the -child1, it will also check -child2 and sometimes it will print -child 2 before -child1. How can I resolve it? Is there any way where I can wait for the else condition to finish and then go to next child? Or is there any way where I can get user detail in just one line of code somehow like this
// rootUser.child.name
How about pre-loading the users, before you start building the HTML?
The outline of that would be something like:
on("value"
instead of on("child_added
, so that you get all messages in one go.once("value")
calls. Note that once()
returns a promise, so you can wait to all users to be loaded with Promise.all()
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.