i am using node.js promise for validating either u

2019-08-29 06:43发布

问题:

i want to check either username exist in mongo db or not i want to do it by promise , i am new in node.js please help me to understand actual scenario thanks in advance.

var errorsArr = [];
var promise = username();
promise.then(function(data){
    errorsArr.push({"msg":"Username already been taken."});
},console.error);

username(function(err,data){
    User.findOne({"username":req.body.username},function(err,user) {
        if(err)
            return console.error(err);

        return user;
    });
});

console.log(errorsArr);

回答1:

Mongoose is already promisified, so this will do:

function findUser() {
  return User.findOne({ "username": req.body.username })
    .then(function(user) {
      if (user) {
        // user exists, you can throw an error if you want
        throw new Error('User already exists!');
      }

      // user doesn't exist, all is good in your case
    }, function(err) {
      // handle mongoose errors here if needed


      // rethrow an error so the caller knows about it
      throw new Error('Some Mongoose error happened!');
      // or throw err; if you want the caller to know exactly what happened
    });
}

findUser().then(function() {
  // user doesn't exist, do your stuff

}).catch(function(err) {
  // here, you'll have Mongoose errors or 'User already exists!' error
  console.log(err.message);
});

A Promise is asynchronous so only return the Promise and the caller will "wait" for it to be resolved and handle the errors.