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?
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)
}