-1

Im a new user of Nodejs and Javascript

I have this class :

class Users {
    constructor() {
        this.all;
        this.selectAll();
    }
    async selectAll() {
      await connection.connect(() =>
            connection.query(`SELECT * FROM users`, (err, result) => {
                this.setData(result);
            }),
        );
    }

    setData(res) {
        this.all = res;
    }
}

I want to get result of data from the response function selectAll(); for example:

var db = new Users();
console.log(db.all);

I expected db.all to give me result of selectAll()

Is there any better idea?

Rai Rz
  • 493
  • 9
  • 22
  • You need to use `await`, you are trying to access property before the response is received. – Leau Dec 26 '21 at 21:17
  • I did it does not work. gives me the same result. thanks – Rai Rz Dec 26 '21 at 21:19
  • You need to await `this.selectAll` call and at your instance creation too. – Leau Dec 26 '21 at 21:26
  • @Leau where should use `await` exactly ? – Rai Rz Dec 26 '21 at 21:26
  • But it's really hacky, I suggest you to use an alternative way. – Leau Dec 26 '21 at 21:27
  • Take a look at here https://stackoverflow.com/a/50885340/14346900. – Leau Dec 26 '21 at 21:28
  • @Leau please let me know any better way for this issue. thanks – Rai Rz Dec 26 '21 at 21:28
  • 1
    Don't call `.selectAll` in your constructor. – Leau Dec 26 '21 at 21:30
  • @Leau I'm a new user of the node and javascript. could you please answer this question with your idea? thanks – Rai Rz Dec 26 '21 at 21:33
  • I begin wonder what the point of that entire class is. The ability to access the "return value" (`all`) independent of the function that creates / "returns" the value (`selectAll`) seems just like a source for errors. So why not make this a plain old function. assuming that `const connection = require("mssql")` how about `export async function selectAll() { await connection.connect(); return connection.query\`SELECT * FROM users\`; }` – Thomas Dec 26 '21 at 22:32

1 Answers1

1

You want to await this.selectAll seeing as it is a promise. So you need to make sure it returns a promise. You could make the constructor async to await the selectAll but this is not advised and probably won't work.

Personally, I would just call db.selectAll after creating the instance of users.

Maybe something like this:

File: Users.js

export class Users {
    all = null

    async selectAll() {
        return connection.connect(() =>
            connection.query(`SELECT * FROM users`, (err, result) => {
                this.setData(result);
            })
        );
    }

    setData(res) {
        this.all = res;
    }
}

File: index.js (or anywhere else)

import { Users } from './Users.js'

// Somewhere else in your code in an async function:
const anotherPlace = async () => {
    const db = new Users();
    await db.selectAll();
    console.log(db.all)
}
Steve
  • 4,372
  • 26
  • 37
  • Thanks. but I want to get response data from outside of class easily. I want do it inside the class – Rai Rz Dec 26 '21 at 21:40
  • I understand you want minimal code outside of the class but its a dangerous practice to use async await in a constructor so for the sake of good practices you really should just call that one extra line outside of the class to populate `all`. – Steve Dec 26 '21 at 21:46
  • 2
    @MikelWilliams Well you could make it that `await db.selectAll()` also returns the value; saves a few characters, but it's either this here or making `db.all` itself a Promise. You need to deal outside of `User` with the fact that your DB-request takes time to fulfil and the result ain't available immediately and you have no clue when the value will be available. Except for the Promise. – Thomas Dec 26 '21 at 22:03
  • In that case, you could possibly look into an async getter https://stackoverflow.com/a/39387979/5553768 but that is pretty horrible. I think there is such thing as over-simplifying which ends up making things more difficult in the long run. – Steve Dec 26 '21 at 22:10
  • @Steve I'm using the User Class coz I want to make a code shorter as much as possible. your solution has been used with a long code. If should use an ugly and long code so why developer uses a class ever?!?! – Rai Rz Dec 26 '21 at 22:48
  • 1
    Not sure what to tell you mate, this is much nicer than the alternative. Maybe start here to understand how classes benefit us: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes – Steve Dec 26 '21 at 23:04