【问题标题】:how to access function variable in anonymous function如何在匿名函数中访问函数变量
【发布时间】:2014-02-01 12:58:04
【问题描述】:

我有一个函数

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

【问题讨论】:

  • mogoose.model 是异步函数吗?如果是这样,任何依赖于回调函数结果的事情都必须在in回调中完成。
  • @Barmar 请查看我编辑的问题。我希望这次我清楚了。
  • 您的第一个 return _callback(count) 缺少回调参数。
  • @Barmar 已编辑。我只想从 UserSchema.path.validate 函数中的 emailNotExists() 调用返回真/假。我该怎么做
  • 如果你知道“异步”是什么意思,那为什么不能工作应该很明显了。

标签: javascript variables scope mongoose anonymous


【解决方案1】:

传入一个回调函数:

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

然后访问变量如下:

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

【讨论】:

  • 在我看来,他想做的事情开销太大
  • 但这是正确的方法。如果回调是异步的,则无法立即访问结果。
  • @leblma - 没有太多的 imo 开销,并且比您建议的 (imo) 创建全局变量更好。一切都在这里。
  • @leblma - 开销太大?这甚至意味着什么?
  • @MWay 有一种更简单的方法可以做到这一点,即全局变量。这样代码更干净。
【解决方案2】:

使用此代码:

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(total);

【讨论】:

  • @Sami 这可能是因为你忘了提到计数是异步的。
  • @leblma 很抱歉没有提到异步函数。
【解决方案3】:

试试这个。

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

【讨论】:

  • 如果mongoose.model 异步运行,这将不起作用,我怀疑它确实如此。
  • @kjana83 这不起作用,因为函数是异步的
猜你喜欢
  • 2014-04-09
  • 1970-01-01
  • 1970-01-01
  • 2020-08-19
  • 1970-01-01
  • 2017-04-09
  • 1970-01-01
  • 2013-02-09
相关资源
最近更新 更多