我正在寻找一种更优雅的方法,以便每当get请求到达我的API时更新我的记录。促销活动有时间限制,因此每次有人进入网站时,激活状态都应根据当前日期进行更新。我当前的代码可以运行,但是我可以肯定它太复杂了,并且可能存在严重的性能问题。
exports.getAllPromotions = async (req, res, next) => {
try {
const allPromotions = await Promotion.find({});
allPromotions.forEach(async promotion => {
promotion.isActive = checkIfActive(
promotion.startingDate,
promotion.endingDate
);
await promotion.save();
});
const updatedPromotions = await Promotion.find({});
return res.status(200).json(updatedPromotions);
} catch (err) {
console.log(err);
}
};
答案 0 :(得分:0)
IMO,是否更新get请求中的某些值都没有关系。实际上,我宁愿使用它而不是发送另一个请求,因为第二个请求可能无法到达服务器。
阿洛斯,我相信forEach
不会等待诺言(await
)解决。您可以使用Array.map()
获得预期的结果。这样,您的.save
函数将并行/并行运行。您可以阅读有关Promise.all以及并行或并行运行时的这篇文章。
const allPromotions = await Promotion.find({});
const promises = allPromotions.map(promotion => {
promotion.isActive = checkIfActive(
promotion.startingDate,
promotion.endingDate
);
return promotion.save();
});
await Promise.all(promises);
const updatedPromotions = await Promotion.find({});