0

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"}

  • 2
    There's no need to use `return new Promise()` when the function is declared `async`, since that automatically makes it return a promise. – Barmar Mar 21 '23 at 16:55
  • Thanks didn't know that! I am pretty new to the promise concept :) – Lukas Walter Mar 21 '23 at 16:57
  • i think you need to use `Promise.all()` – Jud3v Mar 21 '23 at 16:57
  • If the promise function calls `reject()` this will be turned into an exception when you `await` it. You should use `try/catch` to detect whether the promise was resolved or rejected. – Barmar Mar 21 '23 at 16:57
  • @Jud3v Why? There aren't multiple promises. – Barmar Mar 21 '23 at 16:58
  • @Barmar Please consider that proper try, catch error handling is not implemented yet :) – Lukas Walter Mar 21 '23 at 17:00
  • That's what you need to do to "check if the object properties were set correctly and return either resolve('done') or resolve('error')" – Barmar Mar 21 '23 at 17:05
  • @Barmar Alright, just like so `if( (this.id != data[0].id) || (this.player1 != data[0].player1) || (...) ) { resolve('error') }`? Any other improvements? – Lukas Walter Mar 21 '23 at 17:12
  • What's wrong with the `if` statement you currently have, that either calls `resolve()` or `reject()`? – Barmar Mar 21 '23 at 17:20
  • @Barmar I thought it makes more sense to check all of the properties, but probably that's not necessary – Lukas Walter Mar 21 '23 at 17:49
  • You should probably just check whether `data.length > 0` – Barmar Mar 21 '23 at 17:53

0 Answers0