Skip to content

Instantly share code, notes, and snippets.

@cmstead
Created September 20, 2015 19:49
Show Gist options
  • Save cmstead/163632c67ba7d6bebeeb to your computer and use it in GitHub Desktop.
Save cmstead/163632c67ba7d6bebeeb to your computer and use it in GitHub Desktop.
Request cache factory in Javascript
var cacheFactory = (function(){
'use strict';
function RequestCache(requestFn){
this.callQueue = queueFactory.build();
this.requestFn = requestFn;
this.dataCache = {
requestSent: false,
response: null
};
}
RequestCache.prototype = {
resolveCache: function(){
var data = this.dataCache.response.data,
error = this.dataCache.response.error;
while(this.callQueue.peek() !== null){
this.callQueue.dequeue()(data, error);
}
},
resolve: function(data, error){
this.dataCache.response = {
data: data,
error: error
};
this.resolveCache();
},
request: function(callback){
var resolve = this.resolve.bind(this);
this.callQueue.enqueue(callback);
if(this.dataCache.response !== null){
this.resolveCache();
}
//Only send the request once.
else if (!this.requestSent) {
this.requestFn(resolve);
}
}
};
function buildCache(requestFn){
return new RequestCache(requestFn);
}
return {
build: buildCache
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment