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;
}
这是我的代码,用于显示所有待处理的好友请求。
return语句在for循环结束之前运行,并且每次实际返回一个空字符串。
我认为问题在于:ref.orderByValue().on("value", function(snapshot) { ....
如何在所有执行完成后强制javascript运行return语句?
答案 0 :(得分:1)
这是正确的方法,首先你需要使用async
库,所以先安装,然后就可以使用这样的代码了。
function getPending(friendships, cb) {
var myTable= "";
var userId = getUserId('username');
async.each(Object.keys(friendships), function(key, callback) {
if(friendships[key].recvId == userId) {
ref.orderByValue().on("value", function(snapshot) {
snapshot.forEach(function(data) {
// 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;
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>"
callback();
});
});
}
}, function(err) {
cb(err, myTable)
})
}
你不能只是简单地返回表,它应该是回调,或者你可以修改返回承诺的方式