Tomas Mudano
Tomas Mudano

Reputation: 44

ForEach loop code not working in promises while using mongoose

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

Answers (2)

Shaharyar
Shaharyar

Reputation: 12439

I recommend you to use Promise.all.

Steps:

  1. Create a list of promises
  2. Pass that list into Promise.all
  3. Wait for Promise.all to resolve

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

Bergi
Bergi

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

Related Questions