ForEach循环代码在使用mongoose时无法在promises中工作

问题描述 投票:0回答:2

大家!我是nodeJs的新手。我最近在一个项目中工作,要求我将数组推入某些值。我写的代码不起作用,我认为它与promises有关。这是我的代码:

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。

感谢先进的任何帮助!汤姆。

javascript node.js
2个回答
2
投票

使用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);
});

0
投票

我建议你使用Promise.all

脚步:

  1. 创建承诺列表
  2. 将该列表传递给Promise.all
  3. 等待Promise.all解决

码:

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

});
© www.soinside.com 2019 - 2024. All rights reserved.