0

I am getting data from my database. This works.

However, there is something wrong with the flow of my code, I think it has to do with async: Why does facturasDotaciones[ ] (almost last line of code) resolve to undefined?

//npm sql DB access module (https://www.npmjs.com/package/mssql)
var sql = require('mssql'); 

//sql config object (username, password, etc)
var config = {
    bla, bla, bla
}

function traerFacturasDotaciones(){ 
            var request2 = new sql.Request(connection);             
            request2.execute('seleccionarFacturasCorreosDotaciones', function(err, response, returnValue) {

                function peluquiarFacturas(facturas){
                    for(var i=0;i<facturas[0].length;i++){  
                        facturas[0][i]["CO"]=facturas[0][i]["CO"].trim();    
                    }
                    return facturas;
                }
                return peluquiarFacturas(response);
            });
}

//get data from server and clean up
var connection = new sql.Connection(config, function(err) {
    var request = new sql.Request(connection);
    request.execute('seleccionarTiendas', function(err, tiendasRet, returnValue) {
        var facturasDotaciones=[];
        facturasDotaciones=traerFacturasDotaciones();
        console.log("facturasDotaciones", facturasDotaciones);
    });
});
quelquecosa
  • 890
  • 1
  • 10
  • 24

2 Answers2

0

traerFacturasDotaciones() doesnt return anything. It calls request2.execute, which calls a callback function passing the response. One option is that you pass facturasDotaciones to traerFacturasDotaciones as argument and set the value inside that function, but even then it will be assigned in asncy manner. Go through request.execute method to see if it returns promise that you can wait on ?

coder
  • 4,458
  • 2
  • 17
  • 23
0

The function traerFacturasDotaciones does not return anything. Note that the return statement is in a callback function given as second parameter to request2.execute. But that callback is executed asynchronously, and your function traerFacturasDotaciones ends before that callback is executed.

trincot
  • 317,000
  • 35
  • 244
  • 286