2

I get stucked while writing my website at this point.

There is a function:

/* check if email already exists in database */
function validateEmailAccessibility(email){

   User.findOne({email: email}).then(function(result){
        if(result!=null){

        }
   });
}

And the question is how the hell I have to return the false when it already exists?

I've tried to do this like that, but obviously second condition is checked until the variable temp is set to false.

/* check if email already exists in database */
function validateEmailAccessibility(email){
   var temp;
   User.findOne({email: email}).then(function(result){
        if(result!=null){
           temp = false;
        }
   });
   if(temp === false) return false;
}

I have no idea what should I do.

Kacper Czyż
  • 41
  • 2
  • 7

1 Answers1

3

You'd need to return a promise in validateEmailAccessibility:

function validateEmailAccessibility(email){

   return User.findOne({email: email}).then(function(result){
        return result !== null;
   });
}

And somewhere in your code:

validateEmailAccessibility(email).then(function(valid) {
  if (valid) {
    alert("Email is valid");
  } else {
    alert("Email already used");
  }
});
Lucas
  • 4,067
  • 1
  • 20
  • 30