I am working on a browser-game in Node.Js and I have this script :
game.js >>
var config = require('./game_config.js');
var mysql = require('mysql');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var connexion = mysql.createConnection({
'host': config.DB_HOST,
'user' : config.DB_USER,
'password' : config.DB_PASS,
'database' : config.DB_NAME
});
var Player = require('./server/class.player.js');
io.on('connect', function(socket) {
console.log('Co');
var player
socket.on('login', function(data) {
connexion.query("SELECT * FROM player WHERE nick = '"+data.login+"' AND pass = '"+data.pass+"'", function(err, rows) {
if (err) {
throw err;
} else {
if (rows.length == 0) {
var dataRet = "LOG";
socket.emit('login', dataRet);
} else {
var p = rows[0];
var dataRet = new Player(p.id, p.nick, p.map_id, p.x, p.y, connexion).toJson();
console.log(dataRet);
}
// Without setTimeout it wouldn't work because the object didn't have the time to instantiate
setTimeout(function() {
socket.emit('login', dataRet);
},1000);
}
});
});
socket.on('disconnect', function(socket) {
console.log('Disco');
});
});
class.Player.js >>
var Player = function (id, name, map_id, x, y, connexion) {
this.id = id;
this.name = name;
this.map_id = map_id ;
this.x = x;
this.y = y;
this.link = connexion;
this.toJson = function () {
return {
'id' : this.id,
'name' : this.name,
'map_id' : this.map_id,
'x' : this.x,
'y' : this.y
};
}
}
module.exports = User;
So basicly, my code works fine thanks to the "setTimeout()" in game.js (for the socket.emit() event). If I don't use it, the object 'dataRet' doesn't have the time to instantiate due to the asynchronousity of Node.js, so the socket emits "undefined" or "null".
So I was thinking, there MUST be a way to listen for an object instantiation in order to emit it through socket.io as soon as it's done.