У меня есть функция, как, как получить доступ к переменной функции в анонимной функции
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
Как я могу получить возвращаемое значение из анонимной функции
EDIT: После добавления обратных вызовов из предложений ниже
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
@Barmar, пожалуйста, см. Мой отредактированный вопрос. Надеюсь, на этот раз я ясно. – Sami
Ваш первый 'return _callback (count)' отсутствует аргумент для обратного вызова. – Barmar