function getPending(friendships) {
var myTable= "";
var userId = getUserId('username');
for(let key in friendships){
if(friendships.hasOwnProperty(key)){
if(friendships[key].recvId == userId) {
// Do Something with it. Access it via users[key]
myTable += "<div class='container'>";
myTable += "<div class='row'>";
myTable += "<div class = 'col-sm-4'>";
var name ="";
var ref = firebase.database().ref().child("Users");
var foundUser = false;
ref.orderByValue().on("value", function(snapshot) {
snapshot.forEach(function(data) {
var user = data.val();
if(user.userId == friendships[key].sendId && foundUser == false) {
name += ("" + user.username);
foundUser = true;
}
});
});
myTable += name + "</div>";
myTable += "<div class = 'col-sm-4'>Be my friend!</div><div class = 'col-sm-4'>"
myTable += "<button>Accept</button><button>Decline</button></div></div></div>"
}
}
}
return myTable;
}
This is my code to show all pending friend requests.
the return statement runs before the for loop is finished and actually returns an empty string each time.
I think the problem lies with the line : ref.orderByValue().on("value", function(snapshot) { ....
How can I force javascript to run the return statement only after all the execution is finished?