문제

I have a function as

 var emailExists = function (email) {
   mongoose.model('User', UserSchema).
    count({
        email: email
    }, function (err, count) {
        if (err) console.log(err);
        return count;// how can i return this count
    });
 };

in another function i call emailExists

 var total = emailExists(email)
 console.log(total); // this gives undefined now 

How can i get the return value from the anonymous function

EDIT: After adding callbacks from suggestions below

var emailNotExists = function (email, _callback) {
 mongoose.model('User', UserSchema).
    count({
        email: email
    }, function (err, count) {
        if (err)
            return _callback(err, null);
        return _callback(null, ((count == 0) ? true : false));
    });
};

Function where it is called

   UserSchema.path('email').validate(function (email) {
   // I need to return true or false value from this function
   // on true the validation will success
   // on false "Email is registered" message will get fired
   emailNotExists(email, function (err, total) {

       // I can retrieve the True/false value here           
       console.log(total);
   });
  }, 'Email is registered');
도움이 되었습니까?

해결책

Pass in a callback function:

var emailExists = function (email, _callback) {
   mongoose.model('User', UserSchema).
    count({
        email: email
    }, _callback);
 };

Then access the variable as follows:

emailExists(email, function(err, total) {
    console.log(total);
});

다른 팁

Use this code:

var total;
var emailExists = function (email) {
   mongoose.model('User', UserSchema).
    count({
        email: email
    }, function (err, count) {
        if (err) console.log(err);
        total = count;
    });
 };

Then you can access it: console.log(total);

Try this.

var emailExists = function (email) {
 var result;
   mongoose.model('User', UserSchema).
    count({
        email: email
    }, function (err, count) {
        if (err) console.log(err);
        result =count;// how can i return this count
    });
  return result;
 };
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top