Skip to content

Instantly share code, notes, and snippets.

@sapegin sapegin/gist:2235116
Created Mar 29, 2012

Embed
What would you like to do?
Caching Ajax requests with $.Deferred
var counters = {
promises: {},
fetch: function(service, url) {
if (!counters.promises[service]) counters.promises[service] = {};
var servicePromises = counters.promises[service];
if (servicePromises[url]) {
return servicePromises[url];
}
else {
var options = services[service],
deferred = $.Deferred(),
jsonUrl = options.counterUrl && options.counterUrl.replace('{PAGE_URL}', url);
if (typeof options.counter === 'function') {
options.counter(jsonUrl, deferred);
}
else if (options.counterUrl) {
$.getJSON(jsonUrl)
.done(function(data) {
try {
var number = data;
if (typeof options.convertNumber === 'function') {
number = options.convertNumber(data);
}
deferred.resolve(number);
}
catch (e) {
throw e;
deferred.reject(e);
}
});
}
servicePromises[url] = deferred;
return deferred.promise();
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.