I have a encountered a problem while learning NodeJS. I am new to javascript so can anybody explain this to me.
I am calling a function from index.js which will returns values fetched from database. But I am getting undefined object on return.
index.js
const cron = require('node-cron');
const app = require('./app');
const port = process.env.PORT || 3000;
require('dotenv').config();
const { getRecentData } = require('./service/getRecentData')
var prev_id = 0;
cron.schedule('*/10 * * * * *', async() => {
var row = await getRecentData();
console.log(row);
var new_id = row["id"];
if (new_id == prev_id){
new_id = prev_id;
}
else{
console.log(row["date_time"]);
prev_id = new_id;
}
})
app.listen(port, () => {
console.log(`Listening: http://localhost:${port}`);
});
getRecentData.js
const e = require("express")
const { Client } = require('pg');
const client = new Client({
user: 'postgres',
host: 'localhost',
database: 'database',
password: 'postgres',
port: 5432,
});
client.connect();
const getRecentData = async () => {
const query = `
SELECT *
FROM test_table order by id desc limit 1
`;
const recentData = await client.query(query, (err, res) => {
if (err) {
console.error(err);
return;
}
return res.rows;
});
return recentData;
}
module.exports = {
getRecentData
}
But I am getting undefined object in index.js when calling getRecentData() function.