0
I’m trying to get back to the view ejs home/index
the vector of objects objArray
, but when exiting the foreach loop and doing all processing of the data I am receiving from the bank the objArray
returns empty.
Follow the code below
const model = require('../../models/home');
module.exports.index = async (app, req, res) => {
let obj = {
id_gt: 0,
id_membro: 0,
nome: '',
escola: '',
presenca: 0,
};
let objArray = [];
let membros = await model.getMembro();
membros.forEach(async membro => {
let presenca = await model.getPresenca(membro.id_membro);
obj = {...membro, presenca: geraPresenca(presenca)}
objArray = [...objArray, obj];
//#1 console.log(objArray) retorna todo o vetor durante o loop
});
console.log(objArray); //#2 retorna = []
res.render('home/index', {objArray});
}
As I highlighted in the code, in #1 the code returns all objects within the array, but in #2, when exiting the loop, the function log returns an empty array.
How can I get to "see" these changes made in foreach and be able to return to the view this my array with all objects?
I read in some articles that I may be working with Closure, but I still can’t generate a solution.
If anyone can help me with that, I’d appreciate it!!
forEach
does not work with asynchronous functions. Probably your problem comes from there.– Luiz Felipe