4
\$\begingroup\$

I have been trying to do a simple query and return the results with node-mysql however I had several problems. Originally I wrote it where there was no promise, but if I tried to access user after just doing a query if returned undefined

The solution I came up with is the following, is this a good way of doing it? I need to wait until the results come back so I can then send a signal to the frontend to say the player is loaded and can play. Do I need to create a new promise for each query? I have a few tables I need to get data from (That can't be done with joins)

class Player {
    constructor(user_id, socket, connection) {
        this.socket = socket;
        this.connection = connection;

        this.loadUser(user_id)
            .then(() => {
                console.log("loaded user", this.user);
            });
    }

    async loadUser(user_id) {
        let _self = this;
        return new Promise((resolve, reject) => {
            _self.connection.query(`SELECT * FROM users WHERE id = ${user_id}`, (err, res) => {
                this.user = res[0];
                resolve()
            });
        })
    }
}
```
\$\endgroup\$
3
1
\$\begingroup\$

Remove the async method call from the constructor, and make the async method return the instance (this):

class Player {
  constructor(user_id, socket, connection) {
    this.socket = socket;
    this.connection = connection;
  }

  async loadUser() {
    let _self = this;
    return new Promise((resolve, reject) => {
      _self.connection.query(`SELECT * FROM users WHERE id = ${this.user_id}`, (err, res) => {
        this.user = res[0];
        resolve(this)
      });
    })
  }
}

Then you can instantiate a new Player and wait for it to load the necessary data from the database, all in one line, like this:

const player = await new Player(user_id, socket, connection).loadUser();

Or like this:

new Player(user_id, socket, connection).loadUser().then(player => {

});
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.