JavaScript and callback nesting

Posted by Jake King on Programmers See other posts from Programmers or by Jake King
Published on 2012-12-12T19:36:22Z Indexed on 2012/12/12 23:19 UTC
Read the original article Hit count: 203

A lot of JavaScript libraries (notably jQuery) use chaining, which allows the reduction of this:

var foo = $(".foo");
foo.stop();
foo.show();
foo.animate({ top: 0 });

to this:

$(".foo").stop().show().animate({ top: 0 });

With proper formatting, I think this is quite a nice syntactic capability. However, I often see a pattern which I don't particularly like, but appears to be a necessary evil in non-blocking models. This is the ever-present nesting of callback functions:

$(".foo").animate({
    top: 0,
}, {
    callback: function () {
        $.ajax({
            url: 'ajax.php',
        }, {
            callback: function () { ... }
        });
    }
});

And it never ends. Even though I love the ease non-blocking models provide, I hate the odd nesting of function literals it forces upon the programmer.

I'm interesting in writing a small JS library as an exercise, and I'd love to find a better way to do this, but I don't know how it could be done without feeling hacky. Are there any projects out there that have resolved this problem before? And if not, what are the alternatives to this ugly, meaningless code structure?

© Programmers or respective owner

Related posts about JavaScript

Related posts about programming-practices