为什么未处理的承诺被拒绝

时间:2019-04-29 00:03:04

标签: javascript node.js mongodb

无论我在使用邮递员向localhost:5000/api/profile/experience发送邮件的请求中,都会收到这些警告

UnhandledPromiseRejectionWarning: ValidationError: Profile validation failed: experience.0.title: Path `title` is required., experience.0.company: Path `company` is required., experience.0.from: Path `from` is required.

即使我没有填写这些字段,我也不会收到错误消息,要求标题,公司和公司值。 这是我的验证js文件

const Validator = require('validator');
const isEmpty = require('./is-empty');


module.exports = function validateExperienceInput(data){
    let errors = {};


    data.title = !isEmpty(data.title) ? data.title : '';
    data.company = !isEmpty(data.company) ? data.company : '';
    data.from = !isEmpty(data.from) ? data.from : '';


    if(Validator.isEmpty(data.title)){
        errors.title = 'Title field is required'
    }


    if(Validator.isEmpty(data.company)){
        errors.company = 'company field is required'
    }



    if(Validator.isEmpty(data.from)){
        errors.from = 'From field is required'
    }

return {
        errors, 
        isValid: isEmpty(errors)
    }
}

这是路由器文件

router.post('/experience', passport.authenticate('jwt',{session: false}), (req,res) => {

    const {errors, isValid} = validateExperienceInput(req.body);

    Profile.findOne({user:req.user.id})
            .then(profile => {
                const newExp = {
                    title: req.body.title,
                    company: req.body.company,
                    location: req.body.location,
                    from: req.body.from,
                    to: req.body.to,
                    current: req.body.current,
                    description: req.body.description
                }

                // Add to exp array 

                profile.experience.unshift(newExp)
                profile.save().then(profile => res.json(profile))
            })
})

我想念什么?

1 个答案:

答案 0 :(得分:1)

您需要向catch()添加findOne()(拒绝处理程序)以处理findOne()中发生的任何错误/拒绝。来自unhandledrejection的Node.js Process文档:

  

每当一个Promise被发出时,就会发出'unhandledRejection'事件   被拒绝并且在转弯内没有错误处理程序附加到promise   事件循环。使用Promises进行编程时,异常是   封装为“拒绝的承诺”。拒绝可能会被捕获并   使用promise.catch()处理并通过Promise传播   链。 “ unhandledRejection”事件可用于检测和   跟踪被拒绝但没有被拒绝的承诺   尚未处理。

router.post(
  "/experience",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    const { errors, isValid } = validateExperienceInput(req.body);

    Profile.findOne({ user: req.user.id })
      .then(profile => {
        const newExp = {
          title: req.body.title,
          company: req.body.company,
          location: req.body.location,
          from: req.body.from,
          to: req.body.to,
          current: req.body.current,
          description: req.body.description
        };

        // Add to exp array

        profile.experience.unshift(newExp);
        profile.save().then(profile => res.json(profile));
      })
      .catch(err => {
        // do something with error here such send error message or logging
        // res.json(err);
      });
  }
);

只要您有catch()来处理任何错误拒绝,基本上就添加一个then()

希望有帮助!