What I am trying to do: I want to write a object method to fetch data from a MySql database and set the object properties according to the result of the MySql query.
I already achieved this behavoiur using async, await and promises. But im not sure if this is the right way to manipulate the object properties in the promise created in async fetchGame(id)
.
My actual question is: Is this the right way of doing it? How should I check if the object properties were set correctly and return either resolve('done')
or resolve('error')
?
Code Structure:
I have a Game
class with the properties id, player1 and player2 and a method called async fetchGame(id)
.
The Game
Object gets initialized in an other file called index.js.
The database connection gets initialized in mySqlConnection.js.
Please notice that proper try, catch error handling is not implemented yet.
object.js:
const db = require('../mySqlConnection');
class Game{
constructor(){
this.id = null;
this.player1 = null;
this.player2 = null;
}
async fetchGame(id){
return new Promise(async (resolve, reject) => {
const sql = "SELECT * FROM `games` WHERE `id`=" +id
let data = await db.promise(sql);
this.id = data[0].id;
this.player1 = data[0].player1;
this.player2 = data[0].player2;
if(this.id != null){
resolve("done");
} else{
reject("error")
}
});
}
}
mySqlConnection.js:
db.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
db.promise = (sql) => {
return new Promise((resolve, reject) => {
db.query(sql, (err, result) => {
if(err){
reject(new Error());
}
else{
resolve(result);
}
});
});
};
module.exports = db
index.js:
async function createGame(){
var firstGame = new Game()
await firstGame.fetchGame(1)
console.log("index.js: " +JSON.stringify(firstGame))
}
createGame();
console.log Output (as expected): index.js: {"id":1,"player1":"NameOfPlayer1","player2":"NameOfPlayer2"}