New to NodeJs. I am having an issue with synchronizing method execution. heres is what I mean, I have a controller which is responsible for: a. Calling a method (in separate JS file) to open database connection and retrieve data. b. It then sends the data to the front end. From my debugging efforts it would appear I am sending the data before the method that opens the connection and gets the data completes. I know this because when the last line of salesController.js executes it gives error 'Cannot read property 'recordsets' of undefined'. In following code snippet dbAccess.js has method that opens the db and gets data. salesController.js then sends that data. Need help with the highlighted portion in salesController.js. Note if it helps I am using sql server as backend.
dbAccess.js
const dbConfig = require('../../nodeApp/dbConfig')
module.exports = {
makeDBAccess: function(sqlString, req, res) {
var sql = require("mssql/msnodesqlv8");
// connect to your database
sql.connect(dbConfig, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query(sqlString, function (err, recordset) {
if (err) console.log(err)
console.log(recordset.recordsets[0]);
console.log(recordset.recordsets[0].length)
return recordset;
});
});
}
}
salesController.js
const express = require('express');
var router = express.Router();
var dbAccess = require('../utility/dbAccess.js')
var utility = require('../utility/readfile.js')
router.get('/totalSales2011', function (req, res) {
var sqlString = utility.readFileFunc("queries/sales2011.sql");
var recordSet = dbAccess.makeDBAccess(sqlString,req,res); **//Get data from database**
res.send(recordSet.recordsets[0]); **//Wait for line above to complete before doing this.**
});
module.exports = router;