How To Avoid Manually Caching A Request That Returned An Error?
Solution 1:
done
and fail
do not support chaining callback results, your return new Promise
is absolutely pointless. Also it looks as if you are trying to use the Promise
constructor antipattern. What your code does it to simply return the ajax promise as-is (which works, as you can chain onto it).
the results are cached even if there's an error
Yes - by storing the promise, the whole request result is cached, not only in the success case.
Should I add a rejection handler, setting itself to null?
Yes, that's exactly what you'll need to do:
var requestService = (function($) {
var cache = {};
functionget(date) {
var params = date ? {'date': date} : {};
return $.getJSON('http://my/url', params);
}
functionfetchData(date) {
if (!cache[date]) {
cache[date] = get(date);
cache[date].fail(function(err) {
cache[date] = null; // retry nexttime
});
}
return cache[date];
}
return {
fetchData: fetchData
};
})(jQuery);
If you want to return a native promise, use
functionfetchData(date) {
if (!cache[date]) {
cache[date] = Promise.resolve(get(date)).catch(function(err) {
cache[date] = null; // retry nexttime
throw err;
});
}
return cache[date];
}
Solution 2:
ok nevermind, that code worked with some adjustments. In my fetchData method I'm checking if the object is empty (so undefined or null) and I've added a fail() method that nullifies the cache[date]. I do the following now:
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) {
// now also checks for nullif ($.isEmptyObject(cache[date])) {
cache[date] = get(date);
}
return cache[date].done(function(myData) {
returnnewPromise(function(resolve,reject) {
resolve(myData);
});
}).fail(function(myData) {
returnnewPromise(function(resolve,reject) {
// nullifies cache[date]
cache[date] = null;
reject(myData);
});
};
return {
fetchData: fetchData
};
})(jQuery);
Post a Comment for "How To Avoid Manually Caching A Request That Returned An Error?"