I am trying to work with a database in node.js I have an async function to check and see if a record exists in the database. Then the function should return true or false.
Currently the function is returning undefined and in the logs I see that the console.log lines that are in that function are being displayed after what should be the returned value from the async function.
Here is my code
const PostgresCheckExist = async (id) => {
try {
console.log(`-=STARTING POSTGRES CHECK EXISTS=-`);
client.query(`SELECT token from oauth where id = '${id}';`, (err, res) => {
console.log(res.rowCount);
const rowCount = res.rowCount;
if (err) throw err;
if (rowCount <= 0) {
console.log(`The row count was ${rowCount}!\nEntered the <= if marker`);
client.end();
console.log(`Made is passed the 'client.end()' call!`);
return false;
} else if (rowCount >= 2) {
client.end();
console.log(`The row count was ${rowCount}!\nEntered the >= if marker`);
throw "ERROR: More than one item returned on for Primary Key. Please check database";
} else {
console.log(`The row count was ${rowCount}!\nEntered the else marker`);
console.log(rowCount);
client.end();
return true;
}
});
} catch (err) {
console.error(err);
}
};
v1.get("", async (req, res) => {
const respone = await PostgresCheckExist(1)
console.log(response);
res.json({ success: false });
});
This is being called from an express router.
Also here is the output from the command
app[web.1]: -=STARTING POSTGRES CHECK EXISTS=-
app[web.1]: undefined
app[web.1]: 0
app[web.1]: The row count was 0!
app[web.1]: Entered the <= if marker
app[web.1]: Made is passed the 'client.end()' call!