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

430
Vistas
Why does an array of objects return undefined, even though the array is clearly not undefined?

I have an array of objects called result, and it is all of the rows inside an SQL database. In order to access all of the users, I have written the following lines:

function getAllUsers() {
    let sql = 'SELECT * FROM usernames';
    db.query(sql, function (err, result) {
        if (err) throw err;
        else {
            console.log(result);
            return result
        }
    });
}

In this function, the console.log(result) returns the following:

[
  RowDataPacket {
    id: 8,
    username: 'username1',
    password: 'password1',
    created: 2022-06-04T18:03:20.000Z
  },
  RowDataPacket {
    id: 9,
    username: 'username2',
    password: 'test123',
    created: 2022-06-04T22:27:08.000Z
 },
 // etc etc etc
 ...
]

Which is all the rows inside the database in an array. However, when I return it and try to console.log() it inside some other function (in this case - I tried in app.listen('3000') but I checked other functions and it gave me the same result) it returns for some reason undefined, even though it should clearly return the array.

app.listen('3000', function () {
    console.log(getAllUsers());
});

// The console.log(getAllUsers()) returns undefined for some unknown reason

What is the reason for this? How can I fix it and return the users? Thanks in advance!

about 4 years ago · Juan Pablo Isaza
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