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!