There's a line of code using next();
in this Express app (for Nodejs) that I don't understand. I wonder if you could clarify.
In index.js, the express app calls a function isLoggedInMiddleware. It doesn't pass any parameters
app.use(sessionHandler.isLoggedInMiddleware);
Here is that function. When it was called, it wasn't passed any parameters, but it's set up to accept three, with next
being the last, which is called as the return value of getUsername.
this.isLoggedInMiddleware = function(req, res, next) {
var session_id = req.cookies.session;
sessions.getUsername(session_id, function(err, username) {
"use strict";
if (!err && username) {
req.username = username;
}
return next();
});
}
This is getUserName which next(); gets passed to as part of the callbak. Can you explain how next(); was being used? what is it in this context? what is it doing?
this.getUsername = function(session_id, callback) {
"use strict";
if (!session_id) {
callback(Error("Session not set"), null);
return;
}
sessions.findOne({ '_id' : session_id }, function(err, session) {
"use strict";
if (err) return callback(err, null);
if (!session) {
callback(new Error("Session: " + session + " does not exist"), null);
return;
}
callback(null, session.username);
});
}