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

429
Visualizações
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 à 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