Place a condition on an exported function in Node.js

Asked

Viewed 78 times

-1

I’m having a pertinent question, I’m starting a project in Lectron where I have to make the connection with two different banks, one location and the other in clouds, in my Node js code, I have two files the index.js where I put the data referring to Electron and another database.js where I will call the database, hence the doubt, when using the module.Exports = Function ..., to export the function to index.js, I cannot use this sporty function to make an if condition where depending on the answer of the first sql I must run the second in another database, follow the code to better understand

database js.

var mysql = require('mysql');
module.exports = function execSQLbd(sqlQry){  
    var connection = mysql.createConnection({
      host     : 'localhost',
      port     : 3306,
      user     : 'teste',
      password : 'teste',
      database : 'teste'
  });
  connection.connect(function(err) {
      // in case of error
      if(err){
          console.log(err.code);
          console.log(err.fatal);
      }
  });
  connection.query(sqlQry, function(error, rows, fields){
      if(error){
          console.log("An error ocurred performing the query.");
          console.log(err);
          return;
      }
      
      nome = rows[0].nome;
      id = rows[0].id;
      connection.end();

      return id;
      //console.log(id);
  }); 
}

When I change the Return to console.log it appears the result of the database, but the problem is to put this result in if, because when I put the condition in index.js it first runs if and then the database function; Thanks in advance to those who can collaborate...

index js.

var execSQLbd = require('./models/db1');
banco1 = new execSQLbd("SELECT * FROM pagamentos WHERE id = '1'");

if (banco1 == 1)
 return true;


const {app, BrowserWindow} = require ('electron');


let mainWindow;

app.on('ready', () =>{
    mainWindow = new BrowserWindow ({

    });

    mainWindow.loadURL(`file://${__dirname}/teste.html`)
});
  • Because you are using new to invoke a function? (new execSQLbd())

  • Regardless of using new, I can’t return the value to use in an if;

2 answers

0

The new should only be used to instantiate class objects, not to invoke functions. Furthermore, this problem is due to the fact that you are performing an asynchronous operation (a database query) without signaling to the Node.js that he must wait for her to complete.

const execSQLbd = require('./models/db1');
const {app, BrowserWindow} = require ('electron');

async (() => {
    // Utilizando esse await, o fluxo só segue quando o resultado de execSQLbd
    // estiver pronto. Sem ele, o fluxo alcança o if antes que a função termine
    const banco1 = await execSQLbd("SELECT * FROM pagamentos WHERE id = '1'");

    if (banco1 == 1)
        return true;

    let mainWindow;

    app.on('ready', () =>{
        mainWindow = new BrowserWindow ({
    });

    mainWindow.loadURL(`file://${__dirname}/teste.html`)
});

Furthermore, I recommend you to avoid using var, by virtue of the Hoisting, which may cause unwanted effects. I recommend the readings:

https://javascript.info/var

https://javascript.info/async-await

0


Alan Juan helped me a lot, I studied more about Promise and async, I chose to import only variables from the db file, so it is easier to understand the code; In the Code below I made a readjustment which worked perfectly;

index js.

const {app, BrowserWindow} = require ('electron');
const conc = require('./models/db1');

function select(query) {
    return new Promise((resolve, reject) => {
        conc.query(query, function (err, rows, fields) {
            if (err) return reject(err)
            id = rows[0].id;
            resolve(id);
        });
    });
}
    async function SqlResponde (codigo) {
        const result = await select(codigo);
        if(result == 2)
        console.log("Deu Certo");
        else  
        console.log("Deu Errado"); 

        console.log(result);        
        //return result;        
    }
  
SqlResponde("SELECT * FROM pagamentos WHERE id = '1'");

let mainWindow;

app.on('ready', () =>{
    mainWindow = new BrowserWindow ({
});

mainWindow.loadURL(`file://${__dirname}/teste.html`);
});

db1.js

const mysql = require('mysql');

  var connection = mysql.createConnection({
      host     : '',
      port     : 3306,
      user     : '',
      password : '',
      database : ''
  });
  connection.connect(function(err) {
      // in case of error
      if(err){
          console.log(err.code);
          console.log(err.fatal);
      }
  });

module.exports = connection;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.