0
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" });

This is my code, the call to User.updateOne() just throws me out of forEach loop to the if condition at the end and users.length is equal to zero. If I remove that User.updateOne() it works just fine.

  • 1
    `forEach` completely ignores the return value of the callback you give it. With an `async` function, that return value is a promise that will be settled **later** when the asynchronous process is complete. You can't just pass `async` functions to things that don't understand them. Instead of `forEach`, either use a `for-of` loop (if you want to process the items one by one, waiting until the previous is done before doing the next), or `await Promise.all(directSponsers.map(/*...*/))` if you want to process them in parallel. – T.J. Crowder Jul 15 '20 at 14:36
  • (Side note: "sponsor" has an "or" rather than an "er" at the end. Some English words are like that, I'm afraid. :-) ) – T.J. Crowder Jul 15 '20 at 14:37
  • 1
    Yep, I knew it after a long time. Thanks, I read that post but didn't get the idea that's why I asked the question here. But now I understand that. – Muhammad Hassan Javed Jul 15 '20 at 14:54

0 Answers0