Problem with asynchronism in Node

0

I'm new to Node ... I have a module that connects to a postgres DB through pg-node. In that I have no problems. My problem is that when calling that module, from another module, and then wanting to use the data that came out of the BD, it says undefined ... I'm almost sure it's because the connection to the DB returns a promise, and the data does not They are available at the time of use. Pego code

PG connection module

module.exports = function (query) {
const { Client } = require ('pg')

const connection = {
 user: 'postgres',
 host: 'localhost',
 database : 'hoteltest',
 password: '1234',
 port: 5432
}

const client = new Client(connection)

 var datos;

 client.connect()
 client.query(query)
   .then (response => {
     datos = response.rows
     console.log(datos)
     return datos
     client.end()
   })
   .catch(err => {
     console.log(err)
     client.end()
   })
}

and so I call this module:

import data from './pg/index.js'

var pgdata;
pgdata = data('SELECT * FROM usuarios')

console.log(pgdata)

Any suggestions? Thanks!

    
asked by amblador 15.11.2018 в 23:34
source

1 answer

0

Even if you have solved it, I told you that you only needed to return the promise of the PG module, I show you what I mean:

module.exports = function (query) {
    const { Client } = require ('pg')

    const connection = {......}

    const client = new Client(connection)

   client.connect()

   return client.query(query) //Tienes que devolver la promesa para poder usarla
      .then (response => {
           client.end()

           return response.rows
      })
      .catch(err => {
           client.end()
      })
}

And remember that you return a promise, therefore:

import data from './pg/index.js'

data('SELECT * FROM usuarios')
    .then(pgdata => { /* lo que necesites realizar */ })
    .catch(err => console.log(err))

I hope that with this example it has helped you to understand Promise a bit, you can also solve it with Async / Await and Promise, search the internet to find many examples, but ask.

Greetings

    
answered by 16.11.2018 / 20:48
source