how to use Promise with express in node.js?

自作多情 提交于 2019-12-02 22:57:51

Try the following, and after please read the following document https://www.promisejs.org/ to understand how the promises work.

var Promise = require('promise');
router.post('/Registration',function(req,res,next) {
    function username() {
        console.log("agyaaa");
        return new Promise(function(resolve,reject) {
            User.findOne({"username":req.body.username}, function(err,user) {
                if (err) {
                    reject(err)
                } else {
                    console.log("yaha b agyaaa");
                    var errorsArr = [];
                    errorsArr.push({"msg":"Username already been taken."});
                    resolve(errorsArr);
                }

            });
        });
    }
    username().then(function(data) {
        console.log(data);
        next();
    });
});

You can have other errors also (or things that shouldn't be done that way). I'm only showing you the basic use of a Promise.

Gokul Thulaseedharan
router.post('/Registration', function(req, res) {
    return User
        .findOne({ username: req.body.username })
        .then((user) => {
            if (user) {
                return console.log({ msg:"Username already been taken" });
            }
            return console.log({ msg: "Username available." });
        })
        .catch((err)=>{
            return console.error(err);
        });
});

you can write a clean code like this. Promise is a global variable available you don't need to require it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!