My current task involves inserting data into my database within a map loop. To ensure that the loop completes before proceeding, I am utilizing an async function to store all results in the variable "practicasAgregadas."
This is how I invoke the function:
insertarPracticas(turno_id, req.body.lista_codigos_practicas, queryInsertarPracticas)
.then(result => {
res.status(200).json({
"Practicas Agregadas": result
})
})
This is the function itself:
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;
}
The initial attempt yields an empty result:
https://i.sstatic.net/FzBo3.png
Here is the corresponding console output:
https://i.sstatic.net/Rvgnk.png
Upon a second attempt, it does return a result, but with three repetitive entries:
https://i.sstatic.net/tkleI.png
Accompanied by the following console output: