I am making a private messaging system with Node.js and socket.io.
I need to send the latest messages between 2 users. Separately both get_messages_between_users function and get_message_user functions works fine. But If I use them like below, messages array is staying empty when socket emits the data. It is normal actually due to asynchronous structure of Javascript but how can I solve this problem?
Here is the code.
function get_message_user(message, callback) {
var sql = "SELECT * from users WHERE id = " + message.from_user
var query = dbh.query(sql, function(err, result) {
callback(message, result[0]);
});
};
function get_messages_between_users(user1, user2, callback) {
var sql = "SELECT id, from_user, to_user, content, msg_date, status FROM messages WHERE ((to_user = "+user1+" AND from_user = "+user2+") OR (to_user = "+user2+" AND from_user = "+user1+")) ORDER BY id ASC LIMIT 20;"
var query = dbh.query(sql, function(err, result) {
callback(result);
});
};
io.on('connection',function (socket) {
//Other stuff for handling clients
socket.on("page messages", function (data) {
var messages = [];
get_messages_between_users(socket.session.user_id, data.to_user, function(result){
for(var i = 0; i < result.length; i++){
get_message_user(result[i], function(message, user){
var obj = {id: message.id, user_id: user.id, username: user.username, avatar:user.avatar_url, content: message.content, msg_date:message.msg_date};
messages.push(obj);
});
}
});
//The problem is messages array is empty here.
socket.emit('message history', JSON.stringify(messages));
});
});
I am using message parameter in get_message_user just for bypassing variable to result.
for...ofloop is what you want, withawait.const query = db.bind('SELECT * FROM whatever WHERE field=?;'). And then, something likequery.execute(['value for the field']);. As for the async loop: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…