javascript - 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。
感谢您在高级方面的任何帮助!汤姆。
解决方案
使用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);
});
推荐阅读
- java - 方法 sendMessageViaCloudSync 在代号一中删除
- php - 外键值的 PHP/MYSQLI insert_id - $id 变量集但在 INSERT 查询中不起作用
- java - 如何修改 spring.redis.host 配置而无需重启 springboot 项目?
- python - Django:什么可能导致在 auth_permission 表中创建重复权限?
- python - 可以从 bigquery.client.query() 查看 2 个结果集吗?
- azure - CosmosDb 查询嵌套数据按根字段过滤
- python - 继续执行代码而不中断循环函数的输出
- windows - 如何通过堡垒主机从我的 Windows 操作系统客户端计算机连接到私有子网中的 EC2 实例。
- pdf - 附件PDF文件(日文)通过VPN上传后损坏
- plugins - 使用 ExtendScript 在 After Effects 中重新加载预渲染预览