Reputation: 3593
I am trying to send data in MEAN Stack in Node/Express from one middleware to another, I have a route set up, where I have 2 named functions, one queries some data and passes it to a second function that should do some other processing on the data... here is my routing function that has the 2 middleware functions on the "get" method:
function DemonstratorRoutes(router) {
var DemonstratorController = require('../controllers/DemonstratorController')
router.route('/Demonstrator')
.get(DemonstratorController.list_all_Demonstrator, DemonstratorController.doSomeStuff)
module.exports = DemonstratorRoutes;
the implementation of the functions are as follows, its just simple stuff for demonstration / try out purpose..:
exports.list_all_Demonstrator = function(req, res,next) {
//console.log(req.body)
Demonstrator.find({}, function(err, demo) {
if (err){
console.log(err);}
else {
res.locals.myvar = demo;
}
});
next();
};
exports.doSomeStuff = function(req,res,next) {
var data;
data = res.locals.myvar
console.log("Dies ist 2te Funktion:", data);
res.send(data);
}
I have seen that example somewhere... however they did implement it otherwise, they just defined anonymous functions one after the other, separated by commas, but I would like to use named functions and use them in the route file as parameters for Express routing function middleware.. However, I have the problem that the data in the second function is "undefined", I dont understand why this does not work, has it to do with function hoisting? Maybe I have to define my functions otherwise? Or is my callback wrong?
Upvotes: 3
Views: 7473
Reputation: 483
Demonstrator.find
is an asynchronous function, so you should call next
in its callback like this
exports.list_all_Demonstrator = function(req, res,next) {
//console.log(req.body)
Demonstrator.find({}, function(err, demo) {
if (err){
console.log(err);
}
else {
res.locals.myvar = demo;
}
next(); // <------------
});
};
exports.doSomeStuff = function(req,res,next) {
var data;
data = res.locals.myvar
console.log("Dies ist 2te Funktion:", data);
res.send(data);
}
Otherwise next
will be called before you assign demo
to res.locals.myvar
Upvotes: 2