0
這裏是我的代碼片段。我正在嘗試獲取我的friends.friendsList的詳細信息,它駐留在用戶集合本身中,並且在那裏插入用戶的ID。所以首先我拿取userId
,然後提取他們的每一個細節。但我的問題是我沒有得到friendsDetails
fetchDetailsfunction
之外的值。我嘗試了很多次。我是新來的節點和帆JS。我認爲它的異步執行問題。我怎麼解決這個問題?執行之前在node.js中執行for循環的外部代碼
getFriendsDetails:function(req,res){
var userId = req.param('id');
var friendsDetails=[];
User.findOne({
id: userId
}).exec(function(err,user){
var friendsIds=user.friends;
friendsIds.forEach(function(id){
User.findOne({
id: id
}).exec(function fetchDetails(err,Userdetails){
var obj={
id:Userdetails.id,
name:Userdetails.name,
pro_pic:Userdetails.profile_pic
}
friendsDetails.push(obj);
console.log(friendsDetails);//Here consoling pushed data correctly.
});
console.log(friendsDetails);//here i am getting null array
});
});
這是正常現象。在這裏閱讀一點,瞭解基本知識:https://www.codementor.io/nodejs/tutorial/manage-async-nodejs-callback-example-code – hlozancic