So,
I am using node and mssql package (sql-server) to query my database.
however I am facing a difficulty to return queries that need to be executed within a loop.
Maybe it's something to do with the way I'm performing the callback. In other queries where I do not need to loop repeat, it works normally.
My controller:
api.contabilizacaoItems = function (req, res, next) {
itensParaEnvio = [];
var dados = req.body;
cont = 1
console.log(dados.items.length);
dados.items.forEach(function (item, key){
item.aprovacao = dados.aprovacao
solicitacaoSqlDAO.contabilizacaoItem(item, function (erro, recordset) {
item.contItem= recordset.recordset;
solicitacaoSqlDAO.aenItem(item, function (erro, recordset) {
item.aenItens= recordset.recordset;
itensParaEnvio[key]= item;
if(cont == dados.items.length) res.status(200).json(itensParaEnvio);
else res.status(404).json("erro");
})
})
});
};
return api;
My DAO
solicitacaoDAO.prototype.contabilizacaoItem = function (item, callback) {
console.log("# PARA CONSULTA contabilizacaoItem# ");
mssql.close();
mssql.connect(this._connection, function (err) {
if (err) {
console.log("# ERRO AO REALIZAR CONEXAO PARA CONSULTA contabilizacaoItem# "+ err);
}
var request = new mssql.Request();
query = "select * from alguma coisa ";
// console.log(query);
request.query(query, function (err, recordset) {
if (err) {
console.log(query);
callback(err,recordset);
} else {
callback(err,recordset);
}
});
});
}
solicitacaoDAO.prototype.aenItem = function (item, callback) {
console.log("# PARA CONSULTA aenItem# ");
mssql.close();
mssql.connect(this._connection, function (err) {
if (err) {
console.log("# ERRO AO REALIZAR CONEXAO PARA CONSULTA aenItem# "+ err);
}
var request = new mssql.Request();
query = "select * from alguma coisa"
// console.log(query);
request.query(query, function (err, recordset) {
if (err) {
console.log(query);
callback(err,recordset);
} else {
callback(err,recordset);
}
});
});
}