0

Im building a nodejs-app with postgres backend. Im using a pool of connections and when I call my DB like this, I expect the last inserted ID to be returned. This works fine, but the code thats calling the function is getting a undefined returned. What could be the problem here?

function LogSmsToDb(messageToLog) {
const text = 'INSERT INTO sms(Sender, Message, CreateDate) VALUES($1, $2, $3) RETURNING smsid'
var datenow = new Date();
const values = [messageToLog.from, messageToLog.message, datenow]

pool.query(text, values, (err, res) => {
    if (err) {
        logger.error('Error saving to db: ' + err);
        console.log('Error saving to db: ' + err);
        return 0;
    }
    else{
      console.log('id' + res.rows[0].smsid) //This gives me the value to console.
        return res.rows[0].smsid;
    }
})

}

calling code:

routes.post('/newsms', function (req, res) {
let sms = req.body;
var smsId = LogSmsToDb(sms); //Value here is undefined.
}

From What I can see the console output seems to be coming in the wrong order, so my first call to console.log is showing up last.

returned id: undefined [ undefined, '1', 1, 2018-02-12T09:51:09.492Z ] id27

Any ideas?

  • `LogSmsToDb` is asynchronous. Because you are returning an object, the reference is getting updated in the console when the result returns. – Agney Feb 12 '18 at 10:00
  • bacause there's no `return` statement in `LogSmsToDb`, your function does not return anything at all – Thomas Feb 12 '18 at 11:00

1 Answers1

0

use promises to solve this issue like this

function LogSmsToDb(messageToLog) {
const text = 'INSERT INTO sms(Sender, Message, CreateDate) VALUES($1, $2, $3) RETURNING smsid'
var datenow = new Date();
const values = [messageToLog.from, messageToLog.message, datenow]
return new Promise(function (resolve, reject){
    pool.query(text, values, (err, res) => {
        if (err) {
            logger.error('Error saving to db: ' + err);
            console.log('Error saving to db: ' + err);
            reject(0)
            //return 0;
        }
        else{
          console.log('id' + res.rows[0].smsid) //This gives me the value to console.
            resolve(res.rows[0].smsid;)
           // return res.rows[0].smsid;
        }
    })
})

calling code

routes.post('/newsms', function (req, res) {
let sms = req.body;
 LogSmsToDb(sms).then((smsId)=>{
    console.log(smsId)//Value here is defined as u expect.
 }); 
}
Fadi Abo Msalam
  • 6,739
  • 2
  • 20
  • 25
  • Thanks for a great explanation, I totally missed the async bit of the PG-driver. Thank you! –  Feb 12 '18 at 13:11