Return to Snippet

Revision: 43611
at March 28, 2011 01:28 by crypticsoft


Initial Code
var cache = {};

function getData( val ){

    // return either the cached value or an
    // jqXHR object (which contains a promise)
    return cache[ val ] || $.ajax('/foo/', {
        data: { value: val },
        dataType: 'json',
        success: function( resp ){
            cache[ val ] = resp;
        }
    });
}

$.when(getData('foo')).then(function(resp){
    // do something with the response, which may
    // or may not have been retreived using an
    // XHR request.
});

Initial URL
http://stackoverflow.com/questions/4869609/how-can-jquery-deferred-be-used

Initial Description
Basically, if the value has already been requested once before it's returned immediately from the cache. Otherwise, an AJAX request fetches the data and adds it to the cache. The $.when/.then doesn't care about any of this; all you need to be concerned about is using the response, which is passed to the .then() handler in both cases.

Deferreds are perfect for when the task may or may not operate asynchronously, and you want to abstract that condition out of the code.

Initial Title
Cache AJAX Response

Initial Tags
jquery, cache

Initial Language
jQuery