I have the basic tedious javascript code to access mssql found in all of the examples with only slight modifications.
var connection = new Connection(config);
connection.on('connect', function(err) {
if (err) {
console.log("error: " + err);
} else {
executeStatement(email);
}
});
connection.connect();
var Request = require('tedious').Request;
function executeStatement(email) {
const req = `SELECT TOP 1 CUST_NO FROM AR_CUST WHERE email_adrs_1 = '${email}';`;
const request = new Request(req, function(err,rowcount,rows) {
if (err) {
console.log(err);
} else {
console.log(`email -> ${email} rowcount= ${rowcount} rows=${rows}`);
result += rows;
}
});
//setTimeout(function(){ const x=0; },10000);
request.on('row', function(columns) {
columns.forEach(function(column) {
if (column.value === null) {
//console.log('NULL');
} else {
console.log(`${column.metadata.colName} ${column.value}`);
result+= column.value + " ";
}
});
console.log(`${email} -> ${result}`);
});
request.on('done', function(rowCount, more) {
console.log(rowCount + ' rows returned');
});
// Close the connection after the final event emitted by the request, after the callback passes
request.on("requestCompleted", function (rowCount, more) {
connection.close();
});
connection.execSql(request);
}
setTimeout(function(){ const x=0; },10000);
//connection.connect();
console.log(`returning ${result} for ${email}`);
When I run it by itself it works and gives me results. When I wrap a function around it and call it, it returns empty results for every call and when the rest of the program is done printing, it prints all of the sql query results that I wanted to go into my report.
How do I get it to wait and give me the results when I need them? and not after everything else is done?