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()
 });
 })
 }
}
```
pacmaninbw
26.2k13 gold badges47 silver badges113 bronze badges
asked Jul 28, 2020 at 17:09
\$\endgroup\$
3
  • \$\begingroup\$ Is node-mysql that the package @node-mysql/mysql? \$\endgroup\$ Commented Jul 28, 2020 at 20:45
  • \$\begingroup\$ No it's github.com/mysqljs/mysql \$\endgroup\$ Commented Jul 28, 2020 at 22:45
  • \$\begingroup\$ Async constructors would solve your problem easily if JavaScript supported them. There's a proposal here: github.com/tc39/proposal-async-init \$\endgroup\$ Commented Aug 10, 2020 at 20:35

1 Answer 1

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 => {
});
answered Aug 10, 2020 at 20:49
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.