我有一個問題,我想解決方案是使用回調。但我不知道如何。 當開始node.js的下面的代碼被調用:在我自己的模塊中實現回調
// 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
我的構造是這樣的:
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);
}
然後我在數據庫中創建一個播放器:
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);
}
});
};
我的猜測是我需要某種形式的回調,但我不知道我將如何做到這一點。向正確的方向小推一下會很棒!
的可能重複[如何從返回值回調函數](http://stackoverflow.com/questions/6847697/how-to-return-value-from-callback-function);簡而言之,''return this.id''不會做你認爲它做的事。 – Louis