首页 > 解决方案 > async await 让我脱离了 forEach 循环 javascript

问题描述

const users = [];
directSponsers.forEach(async (user) => {
   if (user.is_calculated.ds === true) return;

   const updatedUser = await User.updateOne(
     { _id: user._id },
     { $set: { "is_calculated.ds": true } }
  );

  const pack = packages.find(
    (p) => String(p._id) === String(user.packages[0].packageId)
  );
  totalCommission += pack.sponserPrice * pack.commission;
  const userCommission = pack.sponserPrice * pack.commission;
  users.push({
    _id: user._id,
    name: user.name,
    email: user.email,
    total_amount: pack.sponserPrice,
    commission: userCommission,
    direction: user.leg,
  });
});

if (users.length === 0)
  return res
    .status(400)
    .json({ message: "No children to get direct commission from" });

这是我的代码,对的调用只是将我从循环中User.updateOne()抛出到最后的 if 条件并且等于零。如果我删除它就可以了。forEachusers.lengthUser.updateOne()

标签: javascriptnode.jsmongoose

解决方案


推荐阅读