The first GET request, (/not-work), calls a separate function, database(), with some code to connect to a database and return data. This successfully runs the database() function and that function returns data, but const result, does not get that data properly returned. Instead an unfufilled database connection object is returned. The second request however, (/works), runs nearly the exact same code as, just within the GET route itself. This works perfectly. I cannot for the life of me understand why.
const http = require('http');
const express = require('express');
const app = express();
const sql = require('mssql')
const sqlConfig = {
user: 'login',
password: 'pass',
database: 'database',
server: '123.456.789.012'
}
const database = () => {
return sql.connect(sqlConfig,
(err) => {
if (err) console.log(err);
try {
return new sql.Request()
.execute('dbo.SQLProcedure', (err, recordset) => {
if (err) console.log(err)
return recordset;
});
}
catch (err) {
console.log(err)
}
});
}
app.get('/not-work', (req, res) => {
const result = database();
console.log(result);
res.send(result);
});
app.get('/works', (req, res) => {
sql.connect(sqlConfig,
(err) => {
if (err) console.log(err);
try {
new sql.Request()
.execute('dbo.SQLProcedure', (err, recordset) => {
if (err) console.log(err)
res.send(recordset);
});
}
catch (err) {
console.log(err)
res.send(err);
}
});
});
http.createServer(app).listen(888, () => {
console.log('Server listening 888');
});