-1

I have my function who call the DB to do something :

function callQuery(query) {
  db.query(query, (err, res) => {
    if (err) {
      // Error DB connecion
      console.log(err.stack)
    } else {
      // Send back the results
      return(res.rows[0])
    }
  })
}

My problem is when I call this function by :

const idUser = callQuery("INSERT INTO blablabla RETURNING *")

My data is successfully added in the DB, but idUser came null. It should be res.rows[0]

I am using this tutorial (who instead of setting a variable, call console.log) : https://node-postgres.com/features/connecting

Thank you in advance

Tristan Clet
  • 113
  • 1
  • 9
  • 3
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – adiga Feb 01 '19 at 13:11
  • It is because you are not returning the result of db.query. Add return before db.query(...) so that the callQuery function will return the result of db.query – Rohit Nethi Feb 01 '19 at 13:48

1 Answers1

0

I think this is something due to asynchronous

let promisess = new Promise(function(resolve, reject) {
function callQuery(query) {
  db.query(query, (err, res) => {
    if (err) {
      // Error DB connecion
      console.log(err.stack)
    } else {
      // Send back the results
      resolve(res.rows[0])
    }
  })
}
});
promisess.then((res)=> {
your data in res
});