I cannot get result from my updated object list

Asked

Viewed 329 times

1

I am developing the back of a web service and will be my first application in Nodejs v11. Do not notice the lack of separation of 'business rules' with 'bank manipulation' because I am having problems to do this good practice with Firebird. Anyway, let’s get to the code problem:

module.exports = function(express) {

express.get('/folha', (req, res) => {
    const firebird = require('node-firebird');
    const config = express.config.dbconfig; 

    let listaTudo = [{FORA: 1}]; //Atribuí esse objeto pra saber que ele foi inclido FORA!


    firebird.attach(config, (err, db) => { 
        if (err)
            throw err;

        //GET QUANTIDADE FUNCIONARIOS ATIVOS DA EMPRESA
         db.query("SELECT COUNT(*) AS ATIVOS FROM FUNCCONTRATO WHERE CODIGOEMPRESA = '501' AND DATADEM IS NULL", (err, result /*27*/) => {
            if (err)
                throw err;

            listaTudo.push(result[0]); //Alimentando a listaTudo com resultado { ATIVOS: 27 }
            console.log('result:', result);  // [ { ATIVOS: 27 } ]
            console.log('listaTudo:',listaTudo);  // [ { FORA: 1 }, { ATIVOS: 27 } ] 
            listaTudo.push({DENTRO: 2}); //Alimentando a lista com { DENTRO : 2 } 
            console.log('listaTudo:',listaTudo);  // [ { FORA: 1 }, { ATIVOS: 27 } , { DENTRO : 2 } ]

            db.detach(); // DESCONECTA DO BANCO
        });
        console.log(listaTudo); //OBTIDO:  [ { FORA: 1 } ]  ------ ESPERADO: [ { FORA: 1 }, { ATIVOS: 27 } , { DENTRO : 2 } ]
        res.send(listaTudo); //OBTIDO:  [ { FORA: 1 } ]  ------ ESPERADO: [ { FORA: 1 }, { ATIVOS: 27 } , { DENTRO : 2 } ]
    });
});

};

Well, I took a look at Javascript being a code that works synchronously, maybe that’s why he printed out the console.log() and res.send() on lines 27 and 28 respectively not updated as happened within the function db.query('sql, result =>) on lines 15 to 26.

I want to do this because when accessing /folha I want you to return in Sponse a list of results of querys I did, but I’m not able to feed the list, or if I am, I’m not able to access it after feeding it.

Someone understands what can be done?

  • The first thing to do is to post the code as text and not as image. Also enter the version of Node that you are using

  • Thanks for the tip!! I already edited :D

  • Has any response helped solve the problem and can address similar questions from other users? If so, make sure to mark the answer as accepted. To do this just click on the left side of it (below the indicator of up and down votes).

  • Oops, I did it now that you commented. I appreciate the patience, dear fellow UTFPR. As I said, it was my first forum post. I didn’t know what to do after I got the solution.

1 answer

0


The problem is that the request is asynchronous. Or you enter the res.send within the callback of db.query or rewrites using promise:

const firebird = require('node-firebird');

const attach = (config) => {
  return new Promise((resolve, reject) => {
    firebird.attach(config, (err, db) => {
      if (err) reject(err);
      else resolve(db);
    });
  });
};

const query = (db, sql) => {
  return new Promise((resolve, reject) => {
    db.query(sql, (err, result) => {
      if (err) reject(err);
      else resolve(result);
    });
  });
};

const listar = async (req, res, config) => {
  const lista = [{ FORA: 1 }]; //Atribuí esse objeto pra saber que ele foi inclido FORA!
  const db = await attach(config);
  const result = await query(db, "SELECT COUNT(*) AS ATIVOS FROM FUNCCONTRATO WHERE CODIGOEMPRESA = '501' AND DATADEM IS NULL");
  lista.push(result[0]); //Alimentando a lista com resultado { ATIVOS: 27 }
  console.log('result:', result);  // [ { ATIVOS: 27 } ]
  console.log('lista:', lista);  // [ { FORA: 1 }, { ATIVOS: 27 } ]
  lista.push({ DENTRO: 2 }); //Alimentando a lista com { DENTRO : 2 }
  console.log('lista:',lista);  // [ { FORA: 1 }, { ATIVOS: 27 } , { DENTRO : 2 } ]
  db.detach();
  res.send(lista);
};

module.exports = (express) => express.get('/folha', async (req, res) => listar(req, res, express.config.dbconfig));
  • I’m going to have to do a study on Promises and Async/Await from the looks of it. In theory this your refactored code for my problem has to make some change to run here? Because I switched for it and generates an error(s). Anyway, thank you so much for your help and attention (for editing the main post as well)

  • @Thalesh.P.delira what errors?

  • Unhandledpromiserejectionwarning: Typeerror: self.execute is not a Function at Database.query (c: Node-projects Testesbancountersture_modules Node-Firebird lib index.js:1571:10) at Promise (Internal/util.js:290:30) at new Promise (<Anonymous>)at Internal/util.js:289:12 at list (c: Node-projects Testsbancompressed app Routes funcionario.js:9:24) at processTicksAndRejections (Internal/process/next_tick.js:81:5)

  • @Thalesh.P.delira I made a change that may solve the error you described

Browser other questions tagged

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