Streets Ahead

Presents

Interesting Stuff

Node.js tip: Simplify Callbacks

The blog has been relatively quiet lately, so here is a quick post about a little node.js experiment we threw together. Probably the most challenging thing about working with node.js is trying to perform tasks sequentially given it's asynchronous nature. There are a ton of modules out there to help you solve this problem already, but we had an hour free the other day so we decided to solve it ourselves and here is our quick solution.

There are obviously many ways that this can and should be improved, for instance another common annoyance in Node.js is dealing with throwing and catching errors. There is potential for a solution like this to be able to help you out, but we have not included that here.

var Ahead = function()     {        
    this.queue =         [        ]        ;
    this.running = false;
    this.lastDone = null;
    }    

Ahead.prototype.next = function(func)     {        
    var that = this;
    var done = function(payload)         {            
        this.lastDone = payload;
        if(that.queue.length > 0)             {                
            var nextFunc = that.queue.shift();
            nextFunc(done,                 payload);
                    }             else             {                
            that.running = false;
                    }            
            }        

    if(!that.running)         {            
                    that.running = true;
        func(done,             this.lastDone);
            }         else         {            
        this.queue.push(func);
            }        

    return this;
    }    

module.exports = Ahead;

Sample Usage

var Ahead = require('./ahead.js');

var ahead = new Ahead();

ahead.next(function(done)     {        
    setTimeout(function()        {            console.log('test1'); done("blah blah")        },         5000);
    }    ).next(function(done,     payload)     {        
    setTimeout(function()        {            console.log('test2 ' + payload); done()        },         200);
    }    ).next(function(done)     {        
    setTimeout(function()        {            console.log('test3'); done()        },         5000);
    }    ).next(function(done)     {        
    setTimeout(function()        {            console.log('test4'); done()        },         1);    
    }    )

setTimeout(function()    {        
    ahead.next(function()        {            console.log('second chance')        }        );
    },     100000);

As you can see it's very basic and doesn't have many bells or whistles, but it actually works really well for our purposes. Feel free to leave any constructive compliments in the comments below. Thanks for visiting our site and be sure to check back, we hope to be launching a couple of exciting node.js related projects shortly.

blog comments powered by Disqus