LeeTee
LeeTee

Reputation: 6601

JQuery $.getJSON asynchronous workaround - caching ajax results

I am caching the JSON returned from ajax calls and then displaying the results from the cache. My issue is if there is no cache for that Ajax call already, the results only display on refresh. This is down to the fact that ajax is asynchronous but how do I get around that? Ajax async:false has been deprecated so that's not an option. Would the $.getJSON .done() function suffice or is there a better way?

Here is my code so far:

if ((online === true)) {
    //get JSON
    $.getJSON(baseurl + '/wp-json/app/v2/files?filter[category]' + cat + '&per_page=100', function(jd) {
        //cache JSON
        var cache = {
            date: new Date(),
            data: JSON.stringify(jd)
        };
        localStorage.setItem('cat-' + cat, JSON.stringify(cache));
    });
    //if not online and no cached file
} else if ((online === false) && (!cache['cat-' + cat])) {
    alert('There are no cached files.  You need to be online.');
}

//get cached JSON
cache['cat-' + cat] = JSON.parse(localStorage.getItem('cat-' + cat));
var objCache = cache['cat-' + cat].data;
objCache = JSON.parse(objCache); //Parse string to json
//display JSON results from cache
$.each(objCache, function(i, jd) {
    var thumb = jd.file_thumbnail.sizes.medium;
    //.....etc...
    )
}}

Upvotes: 1

Views: 275

Answers (1)

Jaromanda X
Jaromanda X

Reputation: 1

A simple rewrite of your code yields the following:

function cacheAsCacheCan(cat, callback) {
    if (online === true) {
        //get JSON
        $.getJSON(baseurl + '/wp-json/app/v2/files?filter[category]' + cat + '&per_page=100', function(jd) {
            //cache JSON
            var cache = {
                date: new Date(),
                data: JSON.stringify(jd)
            };
            localStorage.setItem('cat--' + cat, JSON.stringify(cache));
        });
        //if not online and no cached file
    } else if ((online === false) && (!cache['cat-' + cat])) {
        callback('There are no cached files.  You need to be online.');
        return;
    }
    //get cached JSON
    callback(null, cache['cat-' + cat] = JSON.parse(localStorage.getItem('cat-' + cat)));
}

cacheAsCacheCan('someCat', function(error, cachedata) {
    if(error) {
        alert(error);
    } else {
        var objCache = cachedata.data;
        objCache = JSON.parse(objCache); //Parse string to json
        //display JSON results from cache
        $.each(objCache, function(i, jd) {
                var thumb = jd.file_thumbnail.sizes.medium;
                //.....etc...
            )
        }
    }
);

Upvotes: 1

Related Questions