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

384
Vistas
Why is this async function returning empty on the first try, but then it returns everything?

I'm trying to insert data to my db, and the query is inside a map loop, so i'm using an async function to wait for the loop to end, and store all the results in my variable "practicasAgregadas".

This is how i call the function:

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

This is the function:

async function insertarPracticas(turno_id, req, queryInsertarPracticas) {
  const res = await Promise.all(req.map(r => {
    connection.query(
      queryInsertarPracticas, [turno_id, r], (error2, row2) => {
        if (error2) {
          console.log("Error al insertar turno detalle (prácticas): " + r + " " + error2);
          practicasNoAgregadas += r + "-";
        } else {
          console.log("Turnos detalle agregados " + r);
          practicasAgregadas += r + "-";
          console.log("practicas " + practicasAgregadas);
        }
      });
    return practicasAgregadas;
  })
  )

  console.log("en async " + res[0]);
  return res;
}

On the first try, it returns empty:

enter image description here

This is the console:

enter image description here

And on the second try, it does return, but it repeats 3 times:

enter image description here

And the console:

enter image description here

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

0

Most modern JS libs that use async functions will return a promise, but will often not return a promise if the callback is supplied.

So assuming connection.query does return a promise, then the code below should do what your after..

async function insertarPracticas(turno_id, req, queryInsertarPracticas) {
    const res = await Promise.all(
        req.map(async (r) => {
            try {
                const row2 = await connection.query(queryInsertarPracticas, [
                    turno_id, r
                ]);
                console.log("Turnos detalle agregados " + r);
                practicasAgregadas += r + "-";
                console.log("practicas " + practicasAgregadas);
            } catch (e) {
                console.log(
                    "Error al insertar turno detalle (prácticas): " +
                        r + " " + error2
                );
                practicasNoAgregadas += r + "-";
            }
            return practicasAgregadas;
        })
    );

    console.log("en async " + res[0]);
    return res;
}

Remember, don't use a callback, or that could indicate to the lib that your not wanting a promise returning.

If for some reason the lib has not been updated for a long while, you will need to promisify the query..

In node, there is a nice utility called promisify https://nodejs.org/api/util.html#utilpromisifyoriginal that will make this bit easier.

eg.

const conQuery = util.promisify(connection.query);
const row2 = await conQuery(queryInsertarPracticas....

If the callback is not in the form (error, result) you would need to use a Promise constructor.. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise , but looking at your code (error2, row2) => that shouldn't be required.

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