Returned object is undefined, using dynamicHelpers
As @Exploit says in his comment, your tags
function makes an async call to query.exec
, which will finish after your tags
function has returned. Express' helpers
and dynamicHelpers
can't be async, so you need to refactor this somehow. One way would be to put it on req
in an earlier middleware or route, and then have a simple dynamicHelper
which returns that:
dynamicHelpers.js:
exports.tags = function(req, res) { return req.tags;};
Middleware (you might not want to do this for all routes, you could look into e.g. Route specific middleware or Route param pre-conditions):
app.use(function(req, res, next) { var environment = require('../environment'); var service = require('../service'); service.init(environment); var model = service.useModel('tag'); var query = model.Tag.find({}); query.exec(function (err, tags) { if (err) { return next(err); } req.tags = tags; next(); });});
It's kinda dirty but you can do this to wait for tags to be set. The solution Linus G Thiel provided is better though because this will block your application.
tags: function(req, res) { var environment = require('../environment'); var service = require('../service'); service.init(environment); var model = service.useModel('tag'); var query = model.Tag.find({}); var _tags = false; query.exec(function (err, tags) { if (err) { console.log(err); // do something } console.log(tags); _tags = tags; }); while(_tags == false); return _tags;}
Have you tried it like this?
exports = function(app) { app.dynamicHelpers({ tags: function(req, res) { var environment = require('../environment'); var service = require('../service'); service.init(environment); var model = service.useModel('tag'); var query = model.Tag.find({}); query.exec(function (err, tags) { if (err) { console.log(err); // do something } console.log(tags); return tags; }); } });}require("helpers")(app);
You need to defined the middleware before the other routes
module.exports = function(app, express, next){ app.configure(function() { app.use(function(req, res, next) { var environment = require('./environment'); var service = require('./service'); service.init(environment); var model = service.useModel('tag'); var query = model.Tag.find({}); query.exec(function (err, tags) { if (err) { return next(err); } req.tags = tags; next(); console.log(req.tags); <--- works fine }); }); // lots of more app.use functions (eg. express.cookieParser());) // ... });};