Problem executing a query on a loop repeat in the Mssql Node

2

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);
      }   
    });
  });
}
    
asked by anonymous 21.08.2017 / 22:06

1 answer

0

Use promises to resolve only when all callbacks is finalized:

api.contabilizacaoItems = function(req, res, next) {
  var itensParaEnvio = [];
  var dados          = req.body;
  var promessas      = [];

  console.log(dados.items.length);

  dados.items.forEach(function(item, key) {
    promessas.push(new Promise(function(resolver, rejeitar) {
      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;

          resolver();
        })
      });
    }));
  });

  Promise.all([true, promessas]).then(function(values) {
    res.status(200).json(itensParaEnvio);
  }).catch(function() {
    res.status(404).json("erro");
  });
};
    
23.08.2017 / 06:41