大家!我是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。
感谢先进的任何帮助!汤姆。
使用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);
});
我建议你使用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 })
});
});