Middleware in NodeJS

Posted March 16th, 2012 by guidone with No Comments

Talking with a collegue of mine I came up with this solution about organizing the code in NodeJS+Express using middlewares.
Consider this example in which we have a simple page that performs two queries and shows the result in a template.
Since everything is asynchronous, we chain in two queries in this way

app.get('/mypage',function(req,res,next) {
   sequelize.search(query1)
      .on('success',function(res_query1) {
         sequelize.search(query2)
            .on('success',function(res_query2) {
               res.render('my_template',{
                  query1: res_query1,
                  query2: res_query2
                  };
               });
         }
   });

There’s nothing wrong with this, the only problem is that as long as the page gets new functionalities, you keep nesting queries and asyncronous callback.
The resulting code could become unreadable after few cycle of releases.
Continue Reading

  • Categories

  • Tags

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 2 other subscribers

  • Twitter

    Flickr Stream