首页 > 解决方案 > ForEach 循环代码在使用 mongoose 时无法在 Promise 中工作

问题描述

每个人!我是 nodeJs 的新手。我最近一直在从事一个项目,该项目需要我将某些值推入数组中。我写的代码不起作用,我认为它与承诺有关。这是我的代码:

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。

感谢您在高级方面的任何帮助!汤姆。

标签: javascriptnode.js

解决方案


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

推荐阅读