Since node.js is not blocking and asynchronous, then in this code:
client.query("SELECT * FROM users", function (error, results, fields) { if (error) {
data from the database may not yet be loaded into the user variable when you try to log into the console. You can check this if you perform the console.log operation in the request, for example:
client.query("SELECT * FROM users", function (error, results, fields) { if (error) {
To pass the result to a variable when the operation is completed, you can associate your client DB call with the function with the callback parameter and set your variable when calling the callback, for example:
function query(sql, callback) { client.query(sql, function (error, results, fields) { if (error) {
The code above is just a concept.
source share