Search code examples
javascriptnode.jsasynchronousexpresschaining

Should I be chaining methods and functions in node.js and Express?


Just like everybody else, it would seem, I have begun to play around with node.js and the Express framework.

Whilst I am reasonably confident with client-side Javascript, relying heavily on JQuery of course, my playing around with node.js is very much exposing my lack of a proper understanding of how Javascript actually works. Hence this question.

Every tutorial I have seen, including those by Mr Holowaychuk himself, do something like this :

var express = require('express'),
    app = express();

app.use(express.methodOverride());
app.use(express.cookieParser());
app.use('/images', express.static(__dirname + '/public/images'));
app.get('/', <do something>);
app.get('/:something', <do something else>)
app.listen(3000);

If I were writing something like this for client-side Javascript I would be tempted to refer to the app object just once and chain any functions or methods, thus producing this :

var express = require('express'),
    app = express();

app.use(express.methodOverride())
   .use(express.cookieParser())
   .use('/images', express.static(__dirname + '/public/images'))
   .get('/', <do something>)
   .get('/:something', <do something else>)
   .listen(3000);

So my question is: are these two functionally different? Am I risking upsetting the gods of asynchrony?

Any help and links to tutorials called ‘Just because you’ve played around with JQuery doesn’t mean you understand anything about Javascript’ will be gratefully received.


Solution

  • Fluent is just one methodology of structuring your API. In essence what you do is return the variable on which the method was called:

    app.use = function(){
        // do stuff here
        return this;
    };
    

    Then you can do the following:

    app.use().use().use();
    

    This obviously only works when the function normally wouldn't return anything.

    So it depends a bit on what you're doing. If you really want to build your API with the fluent-paradigm then go ahead, but make sure you are consistent about it.

    If you don't want to, that's OK too, you will not break anything or make your code less maintable, it's just a style. (in jQuery it works particularly well, because hardly any method on a jQuery object needs to return data)