0

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.

2 Answers 2

2

You need to understand that await works only with Promises. If the function returns a Promise, you can use await. All async functions return a Promise. In your case, client.query is not returning a promise, it has a callback which has it's own execution context, hence return recentData statement is executing before the completion of the client.query method. You can modify your getRecentData method like this

const getRecentData = () => {
    return new Promise((resolve, reject) => {
        const query = `SELECT * FROM test_table order by id desc limit 1`;
        client.query(query, (err, res) => {
            if (err) {
                console.error(err);
                reject(err);
                return;
            }
            resolve(res);
        });
    });
};
Sign up to request clarification or add additional context in comments.

Comments

0

don't use recentData variable

await client.query(query, (err, res) => {
        if (err) {
            console.error(err);
            return;
        }
        if(res){
             return res.rows; 
        }
  });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.