0

Hello could someone inform me how do I return the value of a query to use in another class This is my query:

var pconn = require('./db.js');
var dadosMsg = null
  
 function getValueMsg(){

    pconn.pool.query('SELECT b.numero_serie, b.grupo_msg, b.index_msg, b.valor_msg FROM  bor_msg b LIMIT 1', (err, rows) => {
        if (!err) {
            dadosMsg = rows.rows[0];
            return dadosMsg;
        } else {
            return err;
            console.log(err);
    }
});  

}

I would like to return the query value in this class

var x = require('./dbmsg');

x.getValueMsg();
console.log(x.dadosMsg.valor_msg);

1 Answers1

0

You can use Promise. A Promises are used to handle asynchronous operations in JavaScript

Promise constructor takes only one argument,a callback function. Callback function takes two arguments, resolve and reject Perform operations inside the callback function and if everything went well then call resolve. If desired operations do not go well then call reject.

  function getValueMsg() {

    return new Promise((resolve, reject) => {

        pconn.pool.query('SELECT b.numero_serie, b.grupo_msg, b.index_msg, b.valor_msg FROM  bor_msg b LIMIT 1', (err, rows) => {
            if (!err) {
                dadosMsg = rows.rows[0];
                resolve(dadosMsg);
            } else {
                console.log(err);
                reject(err);
            }
        });

    });
 }

// other file

var x = require('./dbmsg');
//You can consume Promises using then and .catch methods.
x.getValueMsg().then((results)=>{
  console.log(results);
}).catch((err)=>{
  console.log(err);
})
Saurabh Yadav
  • 3,303
  • 1
  • 10
  • 20