Search code examples
node.jsnode-mssql

Node-mssql Hangs After Query


I am having an issue where I am running a node script to retrieve data from SQL Server. It seems I am getting results, but no code is executed after the query is run. Here is what I have so far for code:

var config = {
    user: 'blah',  
    password: 'blah',  
    server: 'blah',  
    database: 'blah'
};

sql.connect(config, err => {

    if(err) { console.log(err); }

    var request = new sql.Request();
    request.query('select * from products', function(err, data){
        console.log(data.recordset);
        ProcessData(data.recordset);                       
    });

});

sql.on('error', err => {
    console.log(err);    
});    

function ProcessData(results){
    for(var i; i < results.length - 1; i++){
        console.log(results[i].sku);
    }
}

Now, I see results in the terminal for console.log(data.recordset), but I never see any results in the terminal from the ProcessData function. Is there something I am missing that is keeping my code from running correctly? Thanks.

Wade


Solution

  • Figured it out.. You just need to close the connection.

    sql.connect(config, err => {
    
        if(err) { console.log(err); }
    
        var request = new sql.Request();
        request.query('select * from products', function(err, data){
            console.log(data.recordset);
            ProcessData(data.recordset);  
            sql.close() // just close the connection and it will exit !
    
        });
    
    });