大家!我是nodeJs的新手。我最近一直在一个项目中工作,该项目要求我将某些值推入数组。我编写的代码无法正常工作,我认为它与promise有关。
这是我的代码:



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 })

});





我需要将Taller.findOne的返回值放入arrayTalleres。

感谢您对高级的任何帮助!
汤姆

最佳答案

使用Promise.all(并避免使用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);
});

关于javascript - 使用 Mongoose 时ForEach循环代码无法在Promise中工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54989722/

10-10 01:36