Double inquiry in a get

0

I must do 2 consult to fill a table in jade but I always take the second query as I do so that I can do the 2 consult and fill the table correctly.

getAnalisisDetallado: function(req, res, next) {
        console.log('Entro aqui');
        var config = require('.././database/config');

        sql.connect(config)
            .then(function() {
                var articulos = null;
                var request = new sql.Request();
                request.query("SELECT t.SI_Articulo, m.SI_Descripcion, t.SI_UM, (CASE WHEN c.SI_OV IS NOT NULL THEN '*' ELSE NULL END) AS SI_OV, t.SI_Ubicacion, t.SI_Existencia, c.SI_Cantidad, c.SI_Cantidad - t.SI_Existencia AS SI_Dif , (c.SI_Cantidad - t.SI_Existencia) * m.SI_Costo_Promedio AS SI_Dif_Dinero FROM SI_Inventario_Teorico_QAD t INNER JOIN SI_Maestro_Ref_QAD m ON m.SI_Num_Articulo = t.SI_Articulo LEFT JOIN SI_Conteo c ON c.SI_Num_Articulo = t.SI_Articulo")
                    .then(function(recordset) {
                        articulos = recordset['recordset'];
                        console.log('Recordset: ' + recordset);
                        console.log('Affected: ' + request.rowsAffected);
                        sql.close();
                        res.render('menu/analisisDetallado', { ListArticulos: articulos });

                    })
                    .catch(function(err) {
                        console.log('Request error: ' + err);
                    });

            })
            .catch(function(err) {
                if (err) {
                    console.log('SQL Connection Error: ' + err);
                }
            });

        sql.close();
        sql.connect(config)
            .then(function() {
                var request = new sql.Request();
                request.query("SELECT Sk_Codigo_Usuario from Sk_Usuarios")
                    .then(function(recordset) {
                        const usuarios = recordset['recordset'];
                        // const usu = usuarios[0];
                        console.log(usuarios);
                        console.log('yuyu: ' + recordset);
                        console.log('Affected: ' + request.rowsAffected);
                        sql.close();
                        res.render('menu/analisisDetallado', { ListArticulos: usuarios });

                    })
                    .catch(function(err) {
                        console.log('Request error: ' + err);
                    });
            })
            .catch(function(err) {
                if (err) {
                    console.log('SQL Connection Error: ' + err);
                }
            });

    }

this is the jade where the table is

  div(class="container aDetallado")
    div(class="row center span10")
      table(id="example-table" class="table table-striped table-hover table-condensed")
        thead
          tr
            th='Articulo'
            th='Descripción'
            th='Um'
            th='Ov'
            th='#Ubic'
            th='Teorico'
            th='Conteo2'
            th='Dif'
            th='Dif $'
            th='Asignar conteo'
            th='Seleccionar'
          tbody
            each Articulos in ListArticulos
              tr
                td= Articulos.SI_Articulo
                td= Articulos.SI_Descripcion
                td= Articulos.SI_UM
                td= Articulos.SI_OV
                td= Articulos.SI_Ubicacion
                td= Articulos.SI_Existencia
                td= Articulos.SI_Cantidad
                td= Articulos.SI_Dif
                td= Articulos.SI_Dif_Dinero
                td
                  select
                    option
                      each usuario in ListUsuario
                        option(value=usuario.Sk_Codigo_Usuario) #{usuario.Sk_Codigo_Usuario}
                td
                  input(type="checkbox")
    
asked by Eduard 27.06.2017 в 15:55
source

2 answers

2

The problem is clear, you have to wait until the two queries to render the page, you are calling res.render twice, and you only have to do this once per request , check the mssql module and it seemed like that worked with promises, in that case you have to make the two requests to sql and save the result, but not to render the page each time, but at the end of the two requests to render the page with the value of the two requests, in the question both use ListArticulos but for the comment I guess that one is ListUsuarios , then after you have all the data you would do:

res.render('menu/analisisDetallado', { 
    ListArticulos: firstSqlRequest,
    ListUsuarios: secondSqlRequest,
});
    
answered by 27.06.2017 / 17:06
source
0

Good, I recommend using the modules async , mssql and debug , you can simplify your code a lot, and with the module debug , you will only get messages on the console when you run it.

So how to put your queries all together in one file.

I give you an example, where I execute two functions with 5 or 6 queries to several databases and a direct query.

router.get('/:id', function(req, res, next) {
    var reqAx = new sql.Request(dbConfig.config)
    async.waterfall([
        function(callback){
            auxFunctions.getInfo1(machineID, 'empresa', function(array1){
                callback(null, Array1);
            });
        },
        function(array1, callback){
            reqAx.query(qrys.qry_messages('grupoX', id,'ent'))
            .then(function (messages){
                callback(null, oftArrayFullInfo, messages)
            })
        },
        function(array1, messages, callback){
            auxFunctions.getInfo2(id, 'empresa', array1, function(array2){
                callback(null, array1, messages, array2);
            });
        }   
    ],
    function(err, array1, messages, array2){
        if(err) {debug('****** ERROR ASYNC: \n %s', err); }
        else{
            if (array1.length>0){
                res.render('info', {title: 'Info', array1, array2, messages});}
            else{ res.redirect('/'); }
        }
    });
});
    
answered by 06.07.2017 в 16:12