简体   繁体   中英

Pass NodeJS callback from exported function to view

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
  });
});

Step probably can help you ?

function method(callback) {
  var err = null;
  var result = 123;
  callback(err, result);
}
function method2(callback) {
  var err = null;
  var result2 = 'abc';
  callback(err, result2);
}

app.get("/", function(req, res) {
  Step(
    function getData() {
      method(this); // this is a callback for the next function on Step
    }, 
    function getAnotherData(err, result) { // err, result is the reply of method()
      req.result = result; // keep result to use on next function
      method2(this);
    },
    function render(err, result2) {
      res.render('view', {
        result: req.result,
        result2: result2
      });
    }
  )
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM