【发布时间】:2019-09-26 08:54:44
【问题描述】:
我有这个代码:
let result = programBenef.map(async item => {
const beneficiary = await Beneficiary.findById(item.beneficiary_id);
delete item.beneficiary_id;
return {
...item,
...beneficiary
};
});
result = await Promise.all(result);
console.log(result);
当我执行 console.log(result) 时,我得到了这个结果:
Promise {
{ '$__': [InternalCache],
isNew: false,
errors: undefined,
_doc: [Object],
'$init': true } },
Promise {
{ '$__': [InternalCache],
isNew: false,
errors: undefined,
_doc: [Object],
'$init': true } }
为什么不返回实际结果,如何解决?
编辑 1: 这是整个功能:
router.get("/getProgramDistr/:id", auth, async (req, res) => {
if (req.user.roles === 1) return res.status(403);
if (!req.params.id) return res.status(400);
const admin_id = req.user.father_id || req.user._id;
const programDistr = await ProgramDistributor.find({
admin_id,
program_id: req.params.id
});
if (!programDistr) return res.status(404);
let result = await programDistr.map(async item => {
const beneficiary = await Distributor.findById(item.distributor_id);
delete item.distributor_id;
return {
...item,
...beneficiary
};
});
result = await Promise.all(result);
// console.log(result, "this is the result");
return res.send(result);
});
我尝试使用 for loop 代替 map 并将 promise 推送到一个数组,然后调用 Promise.all(array) 仍然是相同的结果。
【问题讨论】:
-
你在哪里调用这个函数?请同时显示包装功能。
-
我已经用整个功能更新了帖子
-
看起来您正在记录
result之前 等待并分配Promise.all调用的结果。我建议对 promise 数组和标识符数组使用两个不同的变量,以确保你没有搞砸。 -
顺便说一句,
programDistr.map(…)返回的数组上的await完全是多余的,你应该放弃它。 (但它不应该造成任何伤害,比如导致您声称获得的奇怪日志)。 -
如果我理解你的话,我已经从 programDistr.map(...) 前面删除了 await 并将 Promise.all() 的结果分配给另一个变量并记录了该变量但还是同样的问题@Bergi
标签: dictionary asynchronous mongoose promise async-await