【发布时间】:2019-10-21 01:30:29
【问题描述】:
所以,我是 nodejs 的新手。我不只是想解决这个问题,我也想学习这个概念。
1 奖有许多获奖者。两者都是单独的表。我首先得到与某个 id 相关的奖品列表。我使用 Promises.all() 循环遍历这些奖品,然后针对每个奖品查询获奖者。
这是我的代码:
router.post("/getResult", function (req, res) {
const lottery_id = req.body.lottery_id;
const data = [];
//Find list of prices for given lottery_id. Note the sorting applied here
Prize.find({"lotid": lottery_id}).sort({name: 1})
.then(async function (prizes) {
try {
await Promise.all(prizes.map(async (prize) => {
//Sorting here works fine as confirmed by this log.
console.log(prize.name);
await Winner.find({"id": prize._id})
.then(function (winners) {
data.push({
prize: prize,
winners: winners
});
})
}));
//Sorting here is completely messed up.
// Something wrong with second query "Winner.find() and pushing data
res.send({success: 1, data: data});
} catch (err) {
console.log("Error " + err);
res.send({success: 0, data: err});
}
}).catch(function (err) {
res.send({success: 0, error: err});
})
});
我得到的最终结果不符合应用于奖品的排序。可能是,对于二等奖的查询 Winner.find() 在一等奖之前完成,因此它在一等奖之前被推送到数据中。
【问题讨论】: