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

160
Vistas
How to return a value of an async function when there's a query inside a for

I'm trying to return a value after a for loop has been completed, the for loop is inside an async function. Inside the loop, there's a query that inserts to the db.

The function is working ok, but when i use postman, the response returns empty (even tho the values have been inserted to the db)

Here's how i call the function:

        insertarPracticas(turno_id,req.body.lista_codigos_practicas, queryInsertarPracticas)
        .then( result=> {
                 res.status(200).json({
                      "Practicas Agregadas": result
                    })
                 }
        )

And here's the function:

async function insertarPracticas(turno_id, req, queryInsertarPracticas){
//practicasAgregadas="";
return new Promise((resolve, reject) => {
    for (let i=0; i< req.length; i++){ 
        connection.query(
            queryInsertarPracticas, [turno_id, req[i]],(error2, row2) => { 
                if (error2) {
                    console.log("Error al insertar turno detalle (prácticas): "+req[i] +" "+ error2);             
                    practicasNoAgregadas += req[i] + "-";                   
                }else{
                    console.log("Turnos detalle agregados "+req[i]);
                    practicasAgregadas += req[i] + "-"; 
                    console.log("practicas "+practicasAgregadas);
                }
        });
        console.log("en for "+practicasAgregadas);
    }
    resolve(practicasAgregadas)

    // Or of there was an error
    reject("error");
})

What's happening here is that the function won't wait for the connection query to end, even tho it inserts values to the db, on Postman i get the first result, which is empty:

enter image description here

But i do have the values inserted on my database.

What's the correct way to handle this? I've tried using map instead of for, and now i'm trying with promise, but i'm not sure i'm using it correctly.

Here's the console, where you can see that the console.log("en for" + practicasAgregadas) returns empty, when it should have some values.

about 4 years ago · Santiago Gelvez
2 Respuestas
Responde la pregunta

0

after your map, just use:

await Promise.all(yourArray);
about 4 years ago · Santiago Gelvez Denunciar

0

I don't know how you built your connection file, but you should change it to an async function and await the connection.query

about 4 years ago · Santiago Gelvez 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