Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

133
Views
How to get data from inside a response function in Nods js

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?

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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)
}
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!