I have 2 functions in javascript and I want to set a global variable in a callback and then return it from my main function. I know javascript is async by nature so what would be the best way to do this? I have the code below:
var results="";
function getData() {
var sql = require("mssql");
var dbConfig={
server:"server",
database: "db",
user:"user",
password: "pw"
}
var conn = new sql.Connection(dbConfig);
var req = new sql.Request(conn);
conn.connect(function (err){
if (err) {
console.log(err);
return;
}
req.query("SELECT * FROM table",resultsCallback)
conn.close();
});
return results;
}
function resultsCallback (err, recordset) {
var tableify = require('tableify');
if (err) {
console.log(err);
}
else {
var html = tableify(recordset);
html = html.replace('<table>','');
html = html.replace('</table>',');
results=html;
}
};
resultsis undefined since javascript is async. Thereturnstatement is executed before the callback function is even finished. How would I be able to wait for the callback to finish before returningresults(ensuringresultsis defined before returning it)?undefindedand not""?resultsis empty and was not returned containing the data from thehtmlvariable in the resultsCallback function. I setresultsequal tohtml