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

428
Views
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
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!