0

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.

Jonathan H
  • 7,591
  • 5
  • 47
  • 80
  • Use promises for your async operations and then you can do `a().then(b).then(c)` and avoid increasing nesting. You can't use exceptions inside of async callbacks and expect to catch them outside of the async handler (unless you use promises). – jfriend00 Feb 12 '17 at 17:43
  • @jfriend00 I have read several times about promises, but I am not experienced enough to see the practical implications of your suggestion. Would you mind elaborating in an answer? – Jonathan H Feb 12 '17 at 17:46
  • 1
    There are hundreds of articles written about the advantages of promises for managing async operations. I'd suggest you go find and read a bunch of those rather than asking us to write another one. – jfriend00 Feb 12 '17 at 17:48
  • @jfriend00 Thanks for your help, this is indeed a duplicate. – Jonathan H Feb 12 '17 at 17:52

0 Answers0