Tuesday, 18 December 2018
javascript - Correct way to callback function after all data have been retrieved from mongoDB in Express?
Answer
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);
// }
});
}
});
php - file_get_contents shows unexpected output while reading a file
I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...
-
I would like to split a String by comma ',' and remove whitespace from the beginning and end of each split. For example, if I have ...
-
I have an app which needs a login and a registration with SQLite. I have the database and a user can login and register. But i would like th...
-
I would like to get the JSON data from Coinmarket. I get the data but can't map the Data. below my Code const p = document.q...
No comments:
Post a Comment