I'm developing a NodeJS app and have a function being exported like so:
module.exports = {
userCount: function(done) {
user.count(function(err, count) {
done(count);
});
}
}
What I'm trying to do is pass the callback to a view. This is how I'm currently doing it:
methods.userCount(function(count) {
app.get("/", function(req, res) {
res.render("../views/index", {
userCount: count
});
});
});
That works fine but my problem is there will be multiple functions being exported, therefore, I will need to pass multiple callbacks to the same view.
Is the way I'm currently doing it the best/only way to pass the callback to the view?
The only other way I thought about doing it was to declare a variable and just add the callback to the variable. Something like this:
var num;
methods.userCount(function(count) {
num = count;
});
res.render("../views/index", {
userCount: num
});
But I'm not sure if that's good practice. Is there a better way to do this?
You should call the userCount
function inside the route handler not the other way around:
app.get("/", function(req, res) {
methods.userCount(function(count) {
res.render("../views/index", {
userCount: count
});
});
});
How you calculate the count is an implementation detail that should be inside the userCount
method.
I believe a better approach would be to run the userCount
method as a route middleware and attach the count to res.locals
:
app.use(function(req,res,next) {
// error handling omitted for simplicity
methods.userCount(function(count) {
res.locals.count = count;
next();
});
})
app.get("/", function(req, res) {
res.render("../views/index", {
userCount: res.locals.count
});
});
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加