new to JS so i'm expecting my bug is very easy to fix.
So i've go a function in a users.js
file :
exports.authenticate = function(user){
User.findOne({
'username':user.username,
'password':user.password,
},'username', function (err, dbuser) {
if (err) return handleError(err);
console.log(Boolean(dbuser));
return Boolean(dbuser);
});
}
So i return the value of my dbuser as a boolean : true if he exists, else false. Quite simple no ? But there come the trap..
var userClass = require('./users.js');
var myUser = userClass.create('xxazeddax','azezaeazeazeaz','mazeazeazezaeaze');
var authent = userClass.authenticate(myUser);
console.log(authent);
Here I'm expecting a boolean value because it's the only thing authenticate() can return.. But not , I got undefined. Please, where did I got wrong ?
Your function(user)
aka as authenticate
does not return anything your other function function (err, dbuser)
is a callback function it means that it will be executed when the request is completed, however, since it is a callback funtion this means that the function(err, dbuser)
was not meant to be executed sequentially.
I recommend you this article to understand what is happening
http://www.impressivewebs.com/callback-functions-javascript/
I quick way to see what is going on change your code in this way:
function(user){
User.findOne({'username':user.username,'password':user.password},'username',
function (err, dbuser) {
if (err) return handleError(err);
console.log(Boolean(dbuser));
return Boolean(dbuser);
});
return true; //<-- authenticate will always return true
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.