Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

134
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda