【发布时间】: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