如何在匿名函数中访问函数变量

时间:2014-02-01 12:58:04

标签: javascript variables scope mongoose anonymous

我有一个功能

 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
    });
 };

在另一个函数中,我称之为emailExists

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

如何从匿名函数

获取返回值

编辑: 在添加以下建议的回调后

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));
    });
};

称为

的函数
   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');

3 个答案:

答案 0 :(得分:3)

传入回调函数:

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

然后按如下方式访问变量:

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

答案 1 :(得分:0)

使用此代码:

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

然后你可以访问它:     的console.log(总);

答案 2 :(得分:0)

试试这个。

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;
 };