【问题标题】:Too Many Promises in single nodejs route单个 nodejs 路由中的承诺太多
【发布时间】:2023-01-21 22:29:23
【问题描述】:

我想知道如果其中一个承诺失败,我该如何回滚或取消已经发生的操作。

第二个有没有其他优化代码的方法,需要更多时间来解决。

随着加入的玩家数量的增加,将花费更多的时间有没有什么办法可以优化它

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

【问题讨论】:

    标签: node.js mongodb async-await transactions query-optimization


    【解决方案1】:

    优化: 在 ES7 和 8 中,我们有一个名为 promise all in 的新功能来解决你的问题,最好不要将 forEach 用于你的 await 函数,最好先在新数组中获取所有 id,如下所示:

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

    【讨论】:

      【解决方案2】:

      要回滚操作,请使用 MongoDB 事务

      【讨论】:

        猜你喜欢
        • 2017-02-25
        • 2021-09-05
        • 1970-01-01
        • 2018-09-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多