Within my node.js javascript program, I am working with a (postgres sql) table. My objective is to determine the number of rows in the table and store this value in a variable (n) for further use in the code.
In response to feedback, I have included more surrounding code and attempted to implement the initial solution provided:
db_connnection.query(display_query).then(result => {
io.to(roomId).emit('room-display-update', result.rows);
const queryFunction = async (db_connnection) => {
var n = await db_connnection.query("SELECT COUNT(*) as total FROM waypoint", function(err,Result) {
return parseInt(Result.total);
});
console.log("There are", n, "inside queryfunction");
return n
};
var nn = queryFunction(db_connnection);
console.log("There are", nn, "outside queryfunction");
Despite trying various methods, such as the one above, I continue to face challenges due to my limited coding knowledge. Errors range from type errors to 'undefined' or 'promise' returns.
How can I ensure that the variable n
actually holds the value 2
(in this particular scenario)?
The problematic snippet now appears like so, accompanied by corresponding console.log errors:
var count_query = "SELECT COUNT(*) as total FROM waypoint"
async function Countit(count_query) {
const ioResult = await db_connnection.query(count_query).then(async (result) => {
console.log("There are", result.total, "inside function")
return parseInt(result.total);
})
console.log("There are", ioResult.total, "inside ioResult")
};
var nn = Countit(count_query);
console.log("There are", nn, "outside function");