Using $.Deferred to Group AJAX Requests

I am working on a project that contains a lot of charts. Since the data driving the charts could take some time to load I am making each chart load asynchronously using jQuery’s ajax functions.

This has worked great, but I noticed that some of the charts are using the same dataset, just charted differently causing the same data to be requested multiple times from the server. One way to handle the duplicate requests is to use the jQuery.Deferred() when making requests.

In order to group the requests together I needed a way to determine if I already have one just like the request going through. To make this simple I used a MD5 library and JSON.stringify() to create a hash of the data that I am sending to the server.

If the hash is unique then I add a deferred object and make the ajax call. Otherwise, I bind to the previous deferred object and wait for the request to finish. Since we are using the jQuery Deferred object the callback will still have the data even if there is a gap between the original ajax request.

Here is a simplified example:

Comments

4 Comments so far. Leave a comment below.
  1. Ryan,

    this is another implementation of doing it with an in-memory cache, a local/session storage fallback, falling back to a ajax request fallback
    (that could be served directly from memcached or another server side cache, falling back to actually looking it up in a DB)

    https://gist.github.com/1830827

    • I haven’t really used coffee script yet, but that looks pretty cool.

      I like that it has localstorage/sessionstorage support. That is a nice tweak for caching when the data doesn’t change very much. How do you determine if the localstorage should be refreshed? Or is it meant to be permanent?

      I also like the catch for a ‘full’ scope to remove items to make room.

      It definitely goes hand in hand with a nice server side caching mechanism. The data that my graphs pulls from is only updated one or two times a day so it is going to have some nice caching on the server side :)

  2. Yep, Deferred are awesome for this kind of synchro.

    I would, however, use the jqXHR promise or use pipe if you wanna hide ajax specific parameters. I would also return the promise so that it can be used by code calling getData (spread the coolness).

    I have a gist with what I mean here.

Add Your Comments

Disclaimer
Your email is never published nor shared.
Required
Required
Tips

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <ol> <ul> <li> <strong>

Ready?