Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialKartikey Singh
4,592 PointsCan't understand callback function
UserSchema.statics.authentication = function(email, password, callback){
User.findOne({ email: email})
.exec(function(error, user){
if(error){
return callback(error);
}
else if(!user){
var err = new Error('User not Found');
err.status = 401;
return callback(err);
}
bcrypt.compare(password, user.password, function(error, result){
if(result === true){
return callback(null, user);
}
else{
return callback();
}
});
});
}
User.authentication(req.body.email, req.body.password, function(err, user){
if(err || !user){
//
}
}
I can't understand how callback function can execute with 2 arguments as well as 1. Sorry since I'm a beginner in javascript I really can't understand the flow of control like when the callback function is executed. Please help me out, Thanks
1 Answer
Christopher Debove
Courses Plus Student 18,373 PointsWell that's quite an advanced course :o... Maybe you need to see the basics before.
The callback you're call take 2 parameters. Think of it like that :
let callback = function(error, data) {
// Code of callback;
}
When your calling it with one argument (the error), the parameter error has a value and no data. When your operation is a success you're calling it with null as error and the data.
Nothing too complicated.
But like I said, trying to skip to some advance course like this (with frameworks and third party namespaces) is no good for a beginner. This could discourage you. I really advise you to check the beginner and intermediate courses.