skip to Main Content

I want to know if one of the promises fail how can i rollback or cancel already happened operations.

and 2nd is there any other way to optimize code, it takes more time to resolve.

As the number of joined player will increase it will be taking more time is there any way to optimise it more

route.put("/UpdateResult/:id", Get_User_id, async (req, res) => {
  try {
      const response = await tournamentschema.findByIdAndUpdate(
        req.params.id,
        {
          Game_Name: req.body.Game_Name,
          Total_Players: req.body.Total_Players,
          Prize_Pool: req.body.Prize_Pool,
          Joined_User: req.body.Joined_User,
          Is_Finished: true,
        },
        { new: true, runValidators: true }
      );
      response.Joined_User.forEach(async (Player) => {
        await UserModal.findByIdAndUpdate(
          Player.UserId,
          {
            $inc: {
              Wallet_Coins: Player.Kills * parseInt(response.Prize_Pool),
            },
          },
          { new: true }
        );
      });
      return res.send("Result Updated Sucessfully");
    
  } catch (error) {
    console.log(error.message);
    res.status(500).send(error.message);
  }
});

2

Answers


  1. Chosen as BEST ANSWER

    To rollback Operations use MongoDB Transactions


  2. for optimize :
    in ES7 and 8 we are have new feature called promise all in for your problem its better you don’t use forEach for your await function its better in first you get all your id in new array like this :

    let playerCacheId = []
    response.Joined_User.forEach((Player) => { 
    playerCacheId.push(player.id)
    }
    await Promise.all(playerCacheId .map(playerId => UserModal.findByIdAndUpdate(
              playerId ,
              {
                $inc: {
                  Wallet_Coins: Player.Kills * parseInt(response.Prize_Pool),
                },
              },
              { new: true }
            );
          });
     ))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search