I am working on a browser-game in Node.Js and I have this script :
game.js >>
var config = require(\'./game_config.js\')
This is not related your question per se but this is quite important - you have a huge SQL injection vulnerability and anyone can do anything to your database.
Instead of:
connection.query(
"SELECT * FROM player WHERE nick = '"
+ data.login + "' AND pass = '" + data.pass + "'",
function (err, rows) {
//...
}
);
either use:
connection.escape(data.login)
and connection.escape(data.pass)
in place of data.login
and data.pass
or:
connection.query(
"SELECT * FROM player WHERE nick = ? AND pass = ?", [data.login, data.pass],
function (err, rows) {
// ...
}
);
It is not only safer but also actually much easier to read and understand. See: Escaping query values in node-mysql manual.
Now, back to your question. There is nothing asynchronous about your Player constructor so your problem must be something else. What is strange here us that your Player.js exports User
(that is not defined) and not Player
(that is defined) so I'm surprised it even works at all. Or you maybe posted a different code than what you're actually using which would explain why you have a race condition that is not obvious from the code.
But if your Player constructor was making some asynchronous calls then I would suggest adding a callback argument and calling it from the constructor:
var Player = function (id, name, map_id, x, y, connexion, callback) {
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
};
}
// some async call that you have to wait for
// symbolized with setTimeout:
setTimeout(function () {
if (callback && typeof callback === 'function') {
callback(this);
}
}, 1000);
}
and then you can pass a callback to your constructor, so this:
} 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);
could change to something like:
} else {
var p = rows[0];
var dataRet = new Player(p.id, p.nick, p.map_id, p.x, p.y, connexion, function () {
socket.emit('login', dataRet);
}).toJson();
console.log(dataRet);
}
but here, as I said, nothing is asynchronous and also your dataRet
is already set even before you run the setTimeout so this is not solving your problem, but it is answering your question.