how to use Promise with express in node.js?

hu7sy picture hu7sy · Jan 27, 2016 · Viewed 44k times · Source

I am using Promise with Express.

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

When I log errorsArray, it is empty and I don't know why. I am new in node.js. Thanks in advance.

Answer

anolsi picture anolsi · Jan 27, 2016

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.