I'm new to learning Node.js, so I'm still getting used to asynchronous programming, callbacks and promises. I'm trying to return data from multiple MSSQL queries in one recordset, but most help articles I find are about MySQL.
I tried to follow the steps shown in the accepted answer here: Synchronous database queries with Node.js
In my SQL function, when I print to console, it's showing the object properly. When I return it to my express router and try to print the value it's saying it's undefined.
Here's my MSSQL function:
var config = require('../../db/config');
async function getJobData(jobID) {
const sql = require('mssql');
let sqlResult = {};
var lock = 2;
var finishRequest = function() {
// This prints the values properly
console.log(sqlResult['jobData']['recordset']);
console.log(sqlResult['jobText']['recordset']);
return sqlResult;
}
// first query
try {
await sql.connect(config)
let result = await sql.query(`SELECT * FROM Jobs WHERE JobID = ${jobID}`);
lock -= 1;
sqlResult['jobData'] = result;
sql.close();
if (lock === 0) {
finishRequest();
}
} catch (err) {
// ... error checks
console.log(err);
}
// second query
try {
await sql.connect(config)
let result = await sql.query(`SELECT * FROM JDSectionTxt WHERE JobID = ${jobID} ORDER BY TypeID, OrderID`);
lock -= 1;
sqlResult['jobText'] = result;
sql.close();
if (lock === 0) {
finishRequest();
}
} catch (err) {
// ... error checks
console.log(err);
}
}
module.exports = getJobData;
Here is my express router:
const express = require('express');
//....
const app = express();
//....
// Job Descriptions - Edit
app.get('/jds/edit', (req, res) => {
const getJobData = require("../models/jds/getJobData");
let jobID = 0;
if(req.query.jobID){
jobID = parseInt(req.query.jobID);
}
let jobData = getJobData(jobID);
jobData.then(result => {
//This just prints 'undefined'
console.log(result);
res.render('jds/edit', {
data: result
});
}).catch(err => {
console.log(err);
});
})
What do I need to change here to properly pass the object from my SQL queries so result is not undefined?