I am building my first serious application with Node.js (using hapi), and I noticed a repeating pattern of code that causes deep nesting and duplication. I am trying to get rid of it by better designing my code, and I am looking for advice from people with more experience.
Here is the typical structure of one of my controllers:
// REQUIREMENTS
// FUNCTION DEFINITION
// CONTROLLER BODY
module.exports = function (request, reply) {
DoSomething( args1, function(error1,result1){
if ( ! error1) {
DoSomethingElse( result1, function(error2,result2){
if ( ! error2) {
// etc.
} else {
// FALLBACK 2
}
});
} else {
// FALLBACK 1
}
});
};
You can see that my intention is to apply processing steps sequentially, but because of the "callback-orientation" of the code (which btw, I don't really understand unless the underlying processing is done concurrently), I am forced to nest calls to subsequent steps within each other, and check for errors each time. Additionally in practice, the fallback is often the same, and therefore this causes duplication as well.
Clearly I must be doing something wrong; I don't have a lot of experience with JavaScript, but I cannot imagine people develop large applications with this design. However I am not sure what is the best way of dealing with this; I think using exceptions together with an overall try-catch block could perhaps avoid the duplication part, but it would not solve passing the result of one processing step to the next. Any help or advice greatly appreciated.