ここに私のコードスニペットです。私は私のfriends.friendsListの詳細を取得しようとしているユーザーコレクション内に存在し、そこに私はユーザーのIDを挿入しています。最初に私はuserId
を取り出して、それぞれの詳細を取得しています。しかし、私の問題はの値が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