Arrows + jQuery

Jan 7, 2009 at 5:13AM
Caleb Doxsey

A few months ago I was reading a haskell blog and discovered Arrowlets - a Javascript library based on Haskell's arrows library.

I thought this was interesting for 2 reasons: It demonstrates the progress Javascript has made in becoming a serious programming language (thanks to people like Crockford) and it has the potential to solve a difficult (and common) problem in a simple way.

At least that was the theory. It turned out that arrows are actually kind of hard to understand. After plodding through a few hours of material, I came to the conclusion that it wasn't so much the concept that was difficult as much as the verbiage used to describe it. In that vain I set about writing my own version of the library. The very incomplete first version of this library can be found here: http://code.google.com/p/jquery-arrows/. (It's built on top of jquery for events and ajax)

Here's an example of how ajax would be done:

Occasionally you run into circumstances where you have AJAX calls that depend on other AJAX calls. You don't want to use a synchronous call because that hangs the browser. Rather what you want is for the calls to be made sequentially, though still asynchronously with regard to the browser. Code for that would typically look like this:

$.ajax({
    url: "A",
    success: function() {
        // a
        $a.ajax({
            url: "B",
            success: function() {
                // b
                $a.ajax({
                    url: "C",
                    success: function() {
                        // c
                    }
                })
            }
        })
    }
})

That quickly becomes out of hand. With arrows:

InSequence(
    Ajax({
        url: "A"
    }),
    Ajax({
        url: "B"
    }),
    Ajax({
        url: "C"
    })
);

What's important here isn't so much the amount of typing one has to do, it's the visibility of the interaction between the various components. The flow of control is much clearer in the second example.

Here's a real example:

// Notice the linear representation of an asynchronous program
$.Arrows.InSequence(
    // Hit Twitter
    $.Arrows.Ajax({
        url: "http://search.twitter.com/search.json?q=dogs",
        dataType: "jsonp"
    }),
    // Take the result and return an object that can be fed
    //   into google
    function(result) {
        return {
            url: "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q="
                + encodeURIComponent(result.results[0].from_user)
        };
    },
    // Hit google
    $.Arrows.Ajax({
        dataType: "jsonp"
    }),
    // Log the result
    function(result) {
        console.log(result);
    }
).run();