Wait The End Of Foreach Loop To Render - Javascript
Solution 1:
You aren't properly waiting for all your asynchronous operations to be done before calling res.render()
thus your array is empty or partially populated when you try to use it. So, you need to use the promises to be able to track when everything is done.
You have a couple choices. You can run all your request in parallel or in sequence. I'll show an example of both:
Here's processing all the database requests in parallel. This chains the various promises and use Promise.all()
to know when they are all done. Results in the controles_cadastrados
are not in any particular order, but this will probably run quicker than processing everything sequentially.
router.get('/', (req, res) => {
Controle.find()
.lean()
.then(controles => {
const controles_cadastrados = [];
Promise.all(controles.map(controle => {
returnSensor.find({ id_mac: controle.sensor })
.lean()
.then(sensor => {
controle.sensor_nome = sensor[0].nome;
returnAtuador.find({ id_mac: controle.atuador })
.lean()
.then(atuador => {
controle.atuador_nome = atuador[0].nome;
controles_cadastrados.push(controle);
console.log(controles_cadastrados);
});
});
})).then(() => {
//wait to send the response
res.render('controle/controles', {
controles: controles_cadastrados,
});
});
}).catch(erro => {
console.log('Erro ao carregar controles');
res.sendStatus(500);
});
});
And, here's how you would sequence the operations using async/await
:
router.get('/', async (req, res) => {
try {
let controles = awaitControle.find().lean();
const controles_cadastrados = [];
for (let controle of controles) {
let sensor = awaitSensor.find({ id_mac: controle.sensor }).lean();
controle.sensor_nome = sensor[0].nome;
let atuador = awaitAtuador.find({ id_mac: controle.atuador }).lean()
controle.atuador_nome = atuador[0].nome;
controles_cadastrados.push(controle);
console.log(controles_cadastrados);
}
//wait to send the response
res.render('controle/controles', {
controles: controles_cadastrados,
});
} catch(e) {
console.log(e, 'Erro ao carregar controles');
res.sendStatus(500);
}
});
Also, note that all possible rejected promises or other errors are captured here and a response is always sent to the incoming http request, even when there's an error.
Post a Comment for "Wait The End Of Foreach Loop To Render - Javascript"