Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

javascript - Unhandled promises - express Node js

I have written a simple get call using express and am trying to get some data from mongoose. It seems there is some issue with my code, because I am getting this error when trying this resource:

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

Could somebody explain to me what's wrong with my code block?

question from:https://stackoverflow.com/questions/65912196/unhandled-promises-express-node-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need a try catch

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

Something like this


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...