Javascript function return always undefined -
new js i'm expecting bug easy fix.
so i've go function in 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 return value of dbuser boolean : true if exists, else false. quite simple no ? there come 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 boolean value because it's thing authenticate() can return.. not , got undefined. please, did got wrong ?
your function(user)
a.k.a authenticate
not return other function function (err, dbuser)
callback function means executed when request completed, however, since callback funtion means function(err, dbuser)
not meant executed sequentially.
i recommend article understand happening
http://www.impressivewebs.com/callback-functions-javascript/
i quick way see going on change code in 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 return true }
Comments
Post a Comment