Reputation: 2073
So basically I am trying to carry out function synchronously using next but Its not happening synchronously: Route.JS
router.post('/era',function(req,res,next){
console.log("got request");
controlleri.book(req,res,next);
booking_controller.book(req,res);
console.log("done in server.js");
next();
});
controlleri.book
and booking_controller.book
both have database calls but
Inspite of adding next() in controlleri.book
, booking_controller.book
starts executing before next being called in the first function.
Tell me if both functions are needed.
Edit:
Tried using async library still its not going synchrounosly Code:
router.post('/era',function(req,res){
console.log("got request");
async.series([
function(callback){
console.log("hi");
controlleri.book(req,res);
callback(null);
},
function(callback){
console.log("hias");
booking_controller.book(req,res);
callback(null);
}
]);
Second function begins before completing First one
Upvotes: 1
Views: 104
Reputation: 1272
Use aync library for doinf operations syncronously.
next() is a middleware which tells that the request shouldn't be returned but there are more functions to be applied on the request.The functions it gets to operate are performed asynchronously because that's node's default behaviour.
async.series([
controlleri.book(callback){
// do some stuff ...
callback(null, 'one');
},
booking_controller.book(callback){
// do some more stuff ...
callback(null, 'two');
}
],
// optional callback
function(err, results){
// results is now equal to ['one', 'two']
});
async.series takes an array of functions to be performed in order (synchronously). The callback passed in each function is mandatory.
Upvotes: 0
Reputation: 35501
Both of your functions take req
, res
and next
as their arguments which is a signature for a middleware function. Further, express middleware is executed in order. Why not just make each of your functions into their own middleware and in the execution order you need them in?
// POST executes controlleri.book
// then booking_controller.book,
// then the log code
router.post('/era', controlleri.book, booking_controller.book, function(req, res, next) {
console.log("done in server.js");
});
This way, next
within controlleri.book
will be booking_controller.book
, and next
in booking_controller.book
will be the last method that logs "done in server.js"
Upvotes: 1