Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

129
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda