Skip to content Skip to sidebar Skip to footer

Jquery Deferred Ajax Cache

I read the top answer to this question regarding the use of jQuery Deferred. I'm looping through an array of IDs. For each ID, I need to get data pertaining to it either from an a

Solution 1:

The problem is that your loop will fire all getData calls immediately, but you results are only stored in the cache once the JSON call returns. Thus, the cache is still empty for every call in the loop and each will perform a new JSON request.

Answer : instead of the result store the Deferred object in the cache.

var IDs = ["1", "2", "1", "3", "1"];

var dataCache = {};

functiongetData(id) {
    if (id in dataCache) {
        console.log("Cache hit for ID " + id);
        return dataCache[id];
    } else {
        console.log("Retrieving data for ID " + id);
        var deferred = $.getJSON("http://jsfiddle.net/echo/jsonp/?callback=?", {
            id: id
        }, function(response) {
            console.log("Retrieved data for ID " + id);
        });
        dataCache[id] = deferred;
        return deferred;
    }
}

for (var i=0; i<IDs.length; i++) {
    $.when(getData(IDs[i])).then(function(result) {
        console.log("result: " + result.id);
    });
}

Note: this is working code, you can play with it in jsFiddle.

Post a Comment for "Jquery Deferred Ajax Cache"