I'm coding the local login in NodeJS following this tutorial:
https://scotch.io/tutorials/easy-node-authentication-setup-and-local
In the file config/passport.js
function(req, email, password, done){ process.nextTick(function(){ User.findOne({'local.email' : email}, function(err, user){ if(err) return done(err); if (user){ return done(null, false, req.flash('signupMessage', 'message')); }
I'm rookie in NodeJS and Javascript, and I don't understand how a value like "done" can be a function (return done(err)). Is any system function?
Thanks a lot!
done
is a callback that you need to call once you are done with your work. As you can see it is given in the first line of your code:
function(req, email, password, done){
This means that besides the incoming request you get the user-specified email
and password
. Now you need to do whatever you need to do to verify the login. Somehow you need to tell Passport whether you succeeded or not.
Normally, you may use a return value for this, but in this case the Passport author thought about the option that your check may be asynchronous, hence using a return value would not work.
This is why a callback is being used. Most often callbacks are being called callback
, but this is just for convenience, there is no technical reason to do so. In this case, since the callback is being used for showing that you are done, the Passport author suggested to call it done
.
Now you can either call done
with an error if credential validation failed, or with the appropriate parameters to show that it succeeded.
This works because functions are so-called first-class citizens in JavaScript, i.e. there is no actual difference between code and data: In JavaScript you can pass functions around as parameters and return values as you can with data.
And that's it :-)
In JavaScript, functions are first class objects.
They can be stored in variables and passed around like any other piece of data.
Function declarations create, in the current scope, a variable with the same name as the function.
function call_done(done) { done(); } function some_function () { alert("Ta da"); } call_done(some_function);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With