Problem with mysql, node and module.exports

0

Eh. . . hello all over the world, they'll see I've been learning one day so if I come to say nonsense and be stupid sorry. I have a small site that I am connecting to mysql with node, but to unburden code I wanted to use module as in java but I have problems. The app makes a request to a js that believes that it has a function that connects to a BD and return (I think) the result, when I call the function it returns a null and then does what I request, it is something Very strange maybe I'm not being very descriptive so I'll leave the code, sorry I'm a beginner.

server.js:

const express = require('express');
const mysql = require("./conetionBD");
var app = express();

app.set('view engine','pug');
app.use("/css", express.static(__dirname+"/css"));

app.get('/',(request,reponse)=>{
  console.log("Probando conexcion a mysql . . .");
  const ingredientes = mysql.getIngredients();
  console.log(ingredientes);
  console.log("Prueba terminada");
  //reponse.render('recetas',{ing:ingredientes });
  reponse.writeHead(200,{"Content-type":"text/html"});
  reponse.end();
});

app.listen(8080);
console.log("Servidor en linea");

connectionBD.js:

console.log("----Iniciando conexcion");
const mysql = require('mysql');
var ingredientes = null;
console.log("----Conecatcando");
const con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "zazem18",
  database: "cibus"
});
module.exports =  {
getIngredients: function(){
    var resultado = null;
    con.connect((err)=>{
      console.log("----Obteniendo datos, "+err);
      if(err) console.log("Error al conectarse");
      console.log("----Saltando error");
      con.query("select * from cat_units", (errr,result,field)=>{
        console.log("----Seleccionar datos");
        if(errr)console.log("Error al obtener datos");
        console.log(result);
        resultado = result;
      });
  });
  return resultado;
  }
}

Result in console:

----Iniciando conexcion
----Conecatcando
Servidor en linea
Probando conexcion a mysql . . .
null
Prueba terminada
----Obteniendo datos, null
----Saltando error
----Seleccionar datos
[ RowDataPacket { id_uni: 1, uni_uni: 'cucharada' },
  RowDataPacket { id_uni: 2, uni_uni: 'gramo' },
  RowDataPacket { id_uni: 3, uni_uni: 'kilogramo' },
  RowDataPacket { id_uni: 4, uni_uni: 'libra' },
  RowDataPacket { id_uni: 5, uni_uni: 'litro' },
  RowDataPacket { id_uni: 6, uni_uni: 'onza' },
  RowDataPacket { id_uni: 7, uni_uni: 'onza líquida' },
  RowDataPacket { id_uni: 8, uni_uni: 'taza' },
  RowDataPacket { id_uni: 9, uni_uni: 'pieza' },
  RowDataPacket { id_uni: 10, uni_uni: 'pisca' },
  RowDataPacket { id_uni: 11, uni_uni: 'al gusto' },
  RowDataPacket { id_uni: 12, uni_uni: 'manojo' },
  RowDataPacket { id_uni: 13, uni_uni: 'hoja' },
  RowDataPacket { id_uni: 14, uni_uni: 'Lata' },
  RowDataPacket { id_uni: 15, uni_uni: 'Loncha' } ]
    
asked by Zush 18 12.05.2018 в 07:51
source

1 answer

0

returns null because within getIngredients returns result and result is still null at that time.

but why is it null if you made the connection and the query to the database before?

What happens is that the connection to the database and the response are not immediate, so all the code that is inside the callback of the query is not will run until your database has not responded with result . But the code that is outside as the return resuldato if it is going to run and has not yet run result = result , result will continue being null

The first thing you did was to declare the result as null, which is the value it will have while waiting for the query to run, the database to respond and the code within the query callback to be executed, changing the value to result.

            getIngredients: function(){
                var resultado = null;

Everything that goes inside the con.conect callback will not run until the connection is made or there is an error.

                con.connect((err)=>{
                  console.log("----Obteniendo datos, "+err);
                  if(err) console.log("Error al conectarse");
                  console.log("----Saltando error");

and everything inside the con.query callback will not run until the database has responded with a result or error

                  con.query("select * from cat_units", (errr,result,field)=>{
                    console.log("----Seleccionar datos");
                    if(errr)console.log("Error al obtener datos");
                    console.log(result);
                    resultado = result;
                  });
              });

As you return the result outside the con.query callback, this line will be executed regardless of whether the query was already made or not.

              return resultado;
              }

CONCLUSION and SOLUTION

js is an asynchronous language in which there are many tasks that run in the background while the rest of the code is still running. This behavior is very important to work with files, databases, connections to other servers ...

The solution is NOT to put the return inside the query callback , this problem has many ways to address:

1) write all the code you need inside the query callback.

                con.query("select * from cat_units", (errr,result,field)=>{
                    console.log("----Seleccionar datos");
                    if(errr)console.log("Error al obtener datos");

                    //acá pongo todo mi codigo
                  });

2) pass a callback as a parameter to your function

            getIngredients: function(callback){
                var resultado = null;
                con.connect((err)=>{
                  console.log("----Obteniendo datos, "+err);
                  if(err) console.log("Error al conectarse");
                  console.log("----Saltando error");
                  con.query("select * from cat_units", (errr,result,field)=>{
                    console.log("----Seleccionar datos");
                    if(errr)console.log("Error al obtener datos");

                    callback(result);
                  });
              });
              }

the way to call your function would be for example:

mysql.getIngredients(console.log);

3) using promises ...

    
answered by 12.05.2018 / 17:58
source