I need to populate array with values from DB and only then return it, so how can i make this Synchronous
var convs = Array;
User.find({token: token}).first(function(err, user) {
ConversationData.find({user_id: 1}).each().forEach(function(convData) {
ConversationData.count({conversation_id: convData.conversation_id}, function(err, count) {
if(count == 2) {
var user2;
console.log(convData.user_id);
ConversationData.find({user_id: 2, conversation_id: convData.conversation_id}).first(function(err, usr) {
user2 = usr;
});
Message.find({conversation: convData.conversation_id}, [ "createdAt", "Z" ]).first(function(err, msg){
convs[convData.id].conversation = convData.id;
convs[convData.id].lastMessage = msg.content;
convs[convData.id].lastMessageDate = msg.createdAt;
convs[convData.id].title = user2.name + " " + user2.name;
convs[convData.id].avatar = user2.avatar;
});
} else {
console.log('COUNT = ' + count);
}
});
});
console.log(convs);
What is the context for what you are trying to do? You cannot make async operations synchronous. Instead you must call another function to tell your program that the async operation has completed.
For example, if you are responding to a client request, you can send the response from within your callback once you have the complete result, e.g. response.send(result);
Else, you might call a done()
function or some similar function to pass along the result.
To represent the eventual result in your code, and also free yourself from nested callbacks, look into replacing your callback functions with Promises. e.g.
return User.find({token: token}).then(function(userData){
return Conversation.find({id: userData.id});
}).then(function(conversationData){
return Message.find({conv_id: conversationData.id}); //or response.send(conversationData) etc
})