jQuery deferred ajax cache

安稳与你 提交于 2019-12-02 07:35:34

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.

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

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

var dataCache = {};

function getData(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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!