Reputation: 44
everyone! I am new to nodeJs. I've been working in a project recently that requires me to push into an array certain values. The code I wrote is not working, and I assume it has to do with promises. This is my code:
router.get('/dashboard/misTalleres', ensureAuthenticated, (req, res) => {
let misTalleres = req.user.talleres;
let arrayTalleres = [];
misTalleres.forEach((taller) => {
Taller.findOne({_id: taller})
.then((tallerFound) => {
arrayTalleres.push(tallerFound);
})
.catch(err => console.log(err));
});
console.log(arrayTalleres);
// console.log(arrayTalleres);
res.render('misTalleres', { name: req.user.name })
});
I need to push into arrayTalleres the return values from the Taller.findOne.
Thanks for any help in advanced! Tom.
Upvotes: 0
Views: 74
Reputation: 12439
I recommend you to use Promise.all
.
Steps:
Code:
router.get('/dashboard/misTalleres', ensureAuthenticated, (req, res) => {
const misTalleres = req.user.talleres;
// list of promises
const promise_array = misTalleres.map((taller) => Taller.findOne({ _id: taller }) );
// execute all promises simultaneaously
Promise.all(promise_array).then(arrayTalleres => {
console.log(arrayTalleres);
res.render('misTalleres', { name: req.user.name })
});
});
Upvotes: 0
Reputation: 664256
Use Promise.all
(and avoid forEach
):
let misTalleres = req.user.talleres;
Promise.all(misTalleres.map(taller => {
return Taller.findOne({_id: taller});
})).then(arrayTalleres => {
console.log(arrayTalleres);
res.render('misTalleres', { name: req.user.name })
}, err => {
console.log(err);
});
Upvotes: 2