I've created a module (following Javascript's Module Pattern) that makes an http request, caches and returns the result:
var requestService = (function($) {
var cache = {};
var get = function(date) {
var params = date ? {'date': date} : {};
return $.getJSON('http://my/url', params, function( result ){});
};
var fetchData = function(date) {
if (!cache[date]) {
cache[date] = get(date);
}
return cache[date].done(function(myData) {
return new Promise(function(resolve,reject) {
resolve(myData);
});
});
};
return {
fetchData: fetchData
};
})(jQuery);
My problem is that the results are cached even if there's an error (ex: the host is temporary unreachable). I don't want that to happen.
I thought that the done() function would only be called if the request succeeded, but it's not the case. Should I add a cache[date].fail(), setting itself to null? What I mean:
return cache[date].done(function(myData) {
return new Promise(function(resolve,reject) {
resolve(myData);
});
}).fail(function(myData) {
cache[date] = null;
return new Promise(function(resolve,reject) {
reject(myData);
});
});
Here's how my requestService is called in another module:
requestService.fetchData(myDate).done(function(myData) {
// code when successful
}).fail(function(d, textStats, error) {
// error
});