未处理的承诺 - 表达 Node js

Unhandled promises - express Node js

我已经使用 express 编写了一个简单的 get 调用,并且正在尝试从 mongoose 获取一些数据。我的代码似乎有问题,因为我在尝试此资源时遇到此错误:

(node:92245) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1) (node:92245) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

//Get all workouts user has registered for
router.get(
  "/user-registered-workouts",
  auth.required,
  async function (req, res, next) {
    let payments = await Payment.find({
      participantsUserId: req.payload.id,
      refund: "no",
    });

    let result = [];
    for (let i = 0; i < payments.length; i++) {
      let workoutDoc = await Workout.findById(payments[i].workoutId).populate(
        "paymentInfo",
        "_id status refund participantsUserId"
      );
      let workout = workoutDoc.toObject();

      let trainerProfile = await Profile.findOne({
        userId: workout.TrainersUserId,
      });

      if (!trainerProfile) {
        return res.sendStatus(401);
      }

      trainerProfile = trainerProfile.toProfileJSONFor();
      workout.trainerDetails = trainerProfile;
      workout.paymentUniqueId = payments[i].id;
      result.push(workout);
    }
    res.json({ workouts: result });
  }
);

有人可以向我解释一下我的代码块有什么问题吗?

你需要试一试

//Get all workouts user has registered for
router.get(
  "/user-registered-workouts",
  auth.required,
  async function (req, res, next) {
    try {
      let payments = await Payment.find({
        participantsUserId: req.payload.id,
        refund: "no",
      });

      let result = [];
      for (let i = 0; i < payments.length; i++) {
        try {
          let workoutDoc = await Workout.findById(
            payments[i].workoutId
          ).populate("paymentInfo", "_id status refund participantsUserId");
          let workout = workoutDoc.toObject();

          let trainerProfile = await Profile.findOne({
            userId: workout.TrainersUserId,
          });

          if (!trainerProfile) {
            return res.sendStatus(401);
          }

          trainerProfile = trainerProfile.toProfileJSONFor();
          workout.trainerDetails = trainerProfile;
          workout.paymentUniqueId = payments[i].id;
          result.push(workout);
        } catch (err) {
          res.status(400).send({ message: err });
        }
      }
      res.json({ workouts: result });
    } catch (err) {
      res.status(400).send({ message: err });
    }
  }
);

像这样