Monday, 7 March 2016

javascript - Correct way to callback function after all data have been retrieved from mongoDB in Express?

I'm writing a web application with a message feature.



A Conversation in my app is defined as between 2 distinct users. For example if Adam had just created a profile and sent 1 message to Jane and a 3 messages to Jack. He would have 2 Conversations but 4 Messages total.



In the following code on Express side, I'm attempting to retrieve all the Conversations for a given user in the database.
Once this is completed, send this data to the Angular controller side.

What's the correct way to do this in api.js below, taking into account that JS is asynchronous?



public/javascripts/main_controller.js



var mainApp = angular.module('myApp', ['ngRoute', 'btford.socket-io', 'xeditable']);
...
mainApp.controller('MessagesController', function($scope, $http, userSessionService, socket, focus){
console.log("MessagesController running");
$scope.messageDisplay = '';
$scope.username = userSessionService.getUserSession().username;


$http({
url: '/loadConversations',
// url: '/about',
method: "GET"
})
.success(function(response) {
console.log("success with loadConversations: ", response);
console.log(response[0].data);
});

....
})


routes/api.js:



....



router.route('/loadConversations')
.get(isAuthenticated, function(req, res) {

var result = [];
//Find Conversation with each and all distinct users
for(var i = 0; i < req.user.conversations.length; i++){
Conversation.findOne({'_id': req.user.conversations[i]}, function(err, conversation){
if(err){
console.log(err);
}
if(conversation){
var contactUsername = (conversation.initiatorUsername == req.user.username) ? conversation.responderUsername : conversation.initiatorUsername;
var lastMessage = conversation.messages[conversation.messages.length-1].content;

var dateOfMessage = conversation.messages[conversation.messages.length-1].date;
var resultJSON = {contactUsername: contactUsername,
lastMessage: lastMessage,
dateOfMessage: dateOfMessage};
result.push(resultJSON);

} else {
console.log("conversation not found!");
}
//Below is not working, where should I put res.json(result)?

// if(result.length == req.user.conversations.length){
// res.json(result);
// }
});


}
});

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...