Over a million developers have joined DZone.

My New Favourite JavaScript Trick

DZone's Guide to

My New Favourite JavaScript Trick

· Java Zone
Free Resource

Bitbucket is for the code that takes us to Mars, decodes the human genome, or drives your next car. What will your code do? Get started with Bitbucket today, it's free.

Using returns and callbacks in the same function.

Sounds like crazy talk I know, but hear me out, I have good reason. I think.

Let’s say you want to make several TCP servers in a node.js application. Have to listen on multiple ports or whatever. Using a factory function is your best bet to avoiding code repetition, right?

You end up with something like this:

var server = function (port, callback) {
    var server = net.createServer(function (connection) {});
    server.on("connection", function (socket) {
        socket.on("data", // data stuff);
        socket.on("error", function () {
            console.log("error?", arguments);
        socket.on("close", // cleanup stuff);
    server.on("listening", callback);

Simple. Call a function, give it a port, get notified when server is ready to listen. Never be able to touch the server again.

Wait, that’s not good. What if you want to reference the server later? To close it, for instance.

That’s where using returns alongside callbacks comes in.

Just adding a return server at the bottom of that function lets us do something like this:

var make_servers = function (callback) {
    this.servers = {};
    async.each([5000, 5001, 5002],
               _.bind(function (port, callback) {
                    this.servers[port] = server(port, callback);
               }, this),
               function (err) {
    return this;

I sneakily added the async and underscore libraries because they make life easier.

make_servers will generate three servers listening on ports 5000 to 5002. The async library helped us ensure the main callback is only called once all the servers are ready to listen, and using _.bind let us bind server generation to the current scope.

When this function is done it returns its scope, which now includes references to all the servers, and it will tell your code to keep going when all the servers are ready.

You’d use it something like this:

var stuff = make_servers(function () { // all servers listening });
// stuff.servers can access all servers

If you bind all the callbacks inside server to current scope you can even keep track of connections. You’d end up with something like this:

var server = function (port) {
    var server = net.createServer(function (connection) {});
    server.on("connection", _.bind(function (socket) {
        socket.id = shortid.generate();
        this.connections[port][socket.id] = socket;
        socket.on("data", // data stuff);
        socket.on("error", function () {
            console.log("error?", arguments);
        socket.on("close", _.bind(function () {
            delete this.connections[port][socket.id];
        }, this));
    }, this));
    return function (callback) {
        server.on("listening", callback);
        return server;

Not much has changed. More things were bound to this and the return value became a function because I feel partial application makes this code cleaner.

You’d call the server factory like this now: this.servers[port] = server(port)(callback). The main benefit of this approach is that we can generate servers in a loop and activate them at a later time.

We’ve essentially decoupled server generation and server startup. Might come in handy.

The stuff object from before is now going to have a stuff.connections as well, which references all currently open connections to each port. Neat!

Another trick I sneaked into these examples is Javascript‘s powerful dynamic scoping. Getting semi-random functions to run in the same scope like that can really clean up your code.

At the expense of being almost too clever sometimes. Use at your own peril.

What do you think, is there a cleaner way to implement something like this?

Are you using Bitbucket to accomplish your company's mission? Share your company’s mission with #Forthecode for a chance to be featured on our homepage, our social media channels, or win a free t-shirt!


Published at DZone with permission of Swizec Teller, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}