I have an problem and I guess the solution is using callbacks. But I'm not sure how. When starting node.js the following code gets called:
// create a new player and insert in the database
// the player gets inserted in the database correctly
var player1 = new player();
console.log(player1.id); // undefined
My constructor looks like this:
function Player(id) {
// if we don't have a id, this player needs to be created
this.id = (typeof id !== 'number') ? this.createPlayer() : this.setId(id);
}
Then I create a player in the database:
Player.prototype.createPlayer = function () {
var playerId = 0;
connection.query("INSERT INTO players SET `created_at` = now()", function (err, result) {
if (result) {
playerId = result.insertId;
console.log("Successfully inserted player no. " + playerId);
this.id = parseInt(playerId, 10);
return this.id;
} else {
console.log("Something went wrong: " + err);
}
});
};
My guess is I need some form of callback, but I'm not sure how I will do this. A small push in the right direction would be great!