异步等待moongose节点js

时间:2017-05-06 08:58:52

标签: javascript node.js promise async-await

我在处理下面的代码时遇到了es6 async / await的问题。问题是如果在保存期间发生任何错误,它不会抛出任何错误(比如我对密码进行验证并使用try / catch),那么我是否需要使用promise then / catch或者有什么方法吗? / p>

 try {

        var response = {response_code:1,response_message:"success",response_obj:[]};
        var statusCode =200;
        if(true) {
            const {f_name, mail, social_id, via, l_name} = req.body;


            const existUser = await User.findOne({$or: [{email: mail}]});

            if (existUser != null) {
                var err = new Error("User Already Exists");
                err.status  = 400;
                throw err;
            }
            const ref_id =   await  UserUtils.makeRefId();
            const verification_code =  UserUtils.generateVerificationCode();

            var newUser = new User({
                firstname : f_name,
                lastname  : l_name,
                password : "dsadasdas",
                social:{social_id : social_id,
                             via : via},
                email : mail,
                ref_id : ref_id,
                verification_code : verification_code,
                role :"USER",
                loc: {type: "Point", coordinates: [0, 0]},
                provider: 'local',
            });


            const data =  await newUser.save(); //its not throwing any error

            console.log(data);
        }
        else
        {
            const err = new Error("Please Send Required Parameters");
            err.status =  400;
            throw  err;
        }
    }catch(err){
        statusCode  = err.status;
        response.response_code = 0;
        response.response_message = err.message;
    }
    finally
    {
        return res.status(statusCode).json(response);
    }

0 个答案:

没有答案