I'm having this strange problem, there is probably something very basic that I miss here...
I'm coding Javascript in NodeJs with Express.
Consider this simple route.
client.get('/test', function(req, res, next) {
return next(new Error('This is a error'));
console.log ('This code will not be executed');
res.send('This code will not be executed');
});
As you probably see this route will directly call next() and pass control to a error handler. The error will be output (res.json) and the request ended. Only the first row in the route will be executed... Just like it should be.
Lets now change the first row in the router to this:
client.get('/test', function(req, res, next) {
hlpr.deadSimple('stop here', function (err) {
if (err) return next(err);
});
console.log ('I dont want this code to be executed, but it will be...');
res.send('This code shall not be executed either');
});
function deadSimple looks like this and is exported from hlpr.js
module.exports.deadSimple = function (val, callback) {
if (val === 'stop here') {
callback(new Error('This is a error!'));
// I have also tried "return callback(new Error('This is a error!'));"
}
};
If i try this code an error is created and it seems that the Error handler is called, it output the Error, but then is seems like control is passed back to the route handler function!... because the console.log is executed.
Why are my deadSimple function passing control back to the route handler?
And how should i write this to work in the way that i want... That is if deadSimple generate an error, this error will trigger a direct return from the route handler function, pass control to error handler, which output the error... And NOT passing control back to the route handler!
EDIT
There was something very basic i missed here, namely that the return statement in the anonymous function that is passed as a callback only return from itself, and not from the surrounding route handler function.
If I move console.log and res.send into the callback they wont be executed because the callback function is returned before they have a chance of being executed. When the callback contains only synchronous code (as this does), it will be executed completley before the code below the callback gets executed.
To show my point... this works as intended:
client.get('/test', function(req, res, next) {
var foo = null;
hlpr.deadSimple('stop here', function (err) {
foo = err;
});
if (foo) return next(foo);
console.log ('This text WILL not be seen');
res.send('This text WILL not be seen either');
});