Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

117
Vistas
NodeJs item variable in array only takes the first value in a for loop

I am using expressJs to route some POST requests. From the client side I pass an object of objects and in the server I iterate over each of them with a for loop.

My problem, the variable cantidad in the loop only takes the first value instead of being refreshed into the pool.query, but before the pool.query it takes the right value.

So, the line below is ok.

console.log("cantidad before query: " + cantidad);

But the line below is bad. It has the first value.

console.log("cantidad in query: " + cantidad);

This is part of my code.

for (var key in objects) {
if (objects.hasOwnProperty(key)) { 
    ...
    console.log("cantidad before query: " + cantidad);
    pool.query(qProducto,idProducto, function (error, results, fields {
    if (error) {
    ...
} else {
    console.log("cantidad in query: " + cantidad);
    ...

This is the full POST in ExpressJs.

app.post("/commanda", function (req, res) {
var idCuenta = req.body.idCuenta;
var idEmpleado = req.body.idEmpleado;
var fechaRegistro = req.body.fechaRegistro;
var cuenta_mesero = "C:" + idCuenta + ":E:" + idEmpleado;
var objects = req.body.objects;
var element = {};
for (var key in objects) {
  if (objects.hasOwnProperty(key)) {
        var qProducto = "SELECT descripcionProducto FROM PRODUCTO WHERE idProducto = ? ;";
        var descProducto = '';
        console.log("cantidad in commanda2 : " + objects[key].cantidad );
        try {
            pool.query(qProducto, objects[key].idProducto, function (error, results, fields) {
            if (error) {
                console.error(error);
                console.error("Failed with query: " + qProducto);
                res.status(500).end();
                throw error;
            } else {
                console.log("cantidad in commanda4 : " + objects[key].cantidad );
                descProducto = JSON.stringify(results[0].descripcionProducto);
                element = {
                    idProducto:objects[key].idProducto,
                    cantidad:objects[key].cantidad,
                    descProducto:descProducto,
                    cuenta_mesero:cuenta_mesero,
                    fechaRegistro:fechaRegistro
                };
                imprimirOrden(element);
                }
            });
        } catch (error) {
        callback(error);
        }
  }
}
printer.printVerticalTab();
res.status(200).end();
});

This is how an object looks like.

{ '0':
   { idProducto: '28',
      cantidad: '3',
      descProducto: 'Product1',
      precioProducto: '3500',
      precioTotal: 10500,
     '$$hashKey': 'object:345' },
 '1':
   { idProducto: '29',
      cantidad: '2',
      descProducto: 'Product2',
      precioProducto: '4500',
      precioTotal: 9000,
      '$$hashKey': 'object:346' } }
about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

This happens because the function for is synchronous but the function poll.query is asynchronous. What this means is that using the for loop you are essentially queuing some queries. You are not executing them one by one. So the for loop will finish before even one result is returned from the query. If you want to use data from the query for the next iteration you should start using async.js, an npm module that helps you avoid this problems. TL;DR the console log that you think runs in query is actually run before even one query has finished. More information is needed on where you declare the variable cantidad and when you change it to accurately understand the problem.

UPDATE: What I told you at first was quite wrong because of the fact that I misunderstood the in-detention of the else {}. But what I told you already is actually the problem. It was well obfuscated.The for loop finishes before even one query has finished. They are just queued. So the second console.log will have the key of the last key in the loop. If you need logic that requires knowing in which iteration you are you should implement an async function in order to know in which iteration you actually are. If you don't want to use the async library you can use something like this.

First add this function in the bottom of your js file https://pastebin.com/4tR0xaTY

You essentially created an async for loop that you can now know in which iteration you are using loop.iteration(). Then replace your post code with the code written below ( To include the async loop ). https://pastebin.com/YzZU7bqp

about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda