Reputation: 49581
Most of npm packages always use "done" callback function in their page. I have hard time to understand it. For example:
passport.serializeUser(function(user, done) {
done(null, user.id);
});
This is my understanding:
"done" is a callback function so its mission is to hold the result which is "null" and "user.id". If so, what is the point of holding "null"? Can't we just say done(user.id)
?
If my understanding is wrong, what is the interpretation of above code?
Also, that code is written in old javascript. How can we write it in modern javascript with arrow function or if possible with async/await?
I try to write with async/await. Is this correct?
passport.serializeUser(async (user)=>{
return await user.id})
Upvotes: 2
Views: 4639
Reputation: 11950
passport.serializeUser(function(user, done) {
done(null, user.id);
});
same as
passport.serializeUser(function(user, callback) {
callback(null, user.id);
});
In node.js, it is considered standard practice to handle errors in asynchronous functions by returning them as the first argument to the current function's callback. If there is an error, the first parameter is passed an Error object with all the details. Otherwise, the first parameter is null.
For that reason, done's first argument is possible error, second is actual value
Upvotes: 1
Reputation: 44135
It's just a success callback. Nothing special.
You can rewrite it in ES6 like so, using destructuring and arrow functions:
passport.serializeUser(({ id }, done) => done(null, id));
Upvotes: 0