Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript cache http get result

I'm building a webpage, that presents data from database in a table. I would like to use HTTP GET to, well, get the data, but I would like to have it cached (I'm talking about client-side Javascript), so I won't have to send more requests for it.

I tried something with promises:

var get = function(aUrl) {
    return new Promise(function(resolve, reject) {
        var anHttpRequest = new XMLHttpRequest();
        anHttpRequest.onreadystatechange = function() { 
            if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200)
                resolve(anHttpRequest.responseText);
        }

        anHttpRequest.open( "GET", aUrl, true );            
        anHttpRequest.send( null );
    })
}  

this.getTableData = function() {
    get("http://localhost:3000/test")
    .then(function(result) {
        console.log(result);
    })
}

I thought that I could store somewhere the result of the promise, but I can't find a way of doing that and it's probably impossible.

So, let me wrap it up: how can I use HTTP GET just once and have the data stored to reuse it later?


1 Answers

Something like this

var get = (function() {
    var promises = {};
    return function(aUrl, forceReload) {
        if (!promises[aUrl] || forceReload) {
            promises[aUrl] = new Promise(function(resolve, reject) {
                // your code is unchanged in here
            });
        }
        return promises[aUrl];
    }
}());

This will return a new Promise, or the previously one that was created for the same url ... added a forceReload parameter because when I've used such a function, there are legitimate reasons for the logic

I would recommend you reject the promise when appropriate, otherwise you'll just have a perpetually pending promise, yet you should be able to determine eventually that there was an error or a non 200 response - so reject the promise in that case. But that's just a recommendation for sane code

like image 117
Jaromanda X Avatar answered Apr 28 '26 20:04

Jaromanda X



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!