exp-asynccache
Advanced tools
Comparing version
33
index.js
@@ -12,10 +12,20 @@ "use strict"; | ||
var self = this; | ||
function inner(hitFn) { | ||
var resolvedCallback = function (err, hit, cacheHeader) { | ||
if (err) return hitFn(err); | ||
function resolvedCallback(err, hit, cacheHeader) { | ||
if (err) { | ||
if (self.pending[key]) { | ||
self.pending[key].forEach(function (callback) { | ||
setImmediate(callback, err); | ||
}); | ||
delete self.pending[key]; | ||
} | ||
return; | ||
} | ||
// See https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments | ||
var args = new Array(arguments.length); | ||
args[0] = key; | ||
for(var i = 1; i < args.length; ++i) { | ||
for (var i = 1; i < args.length; ++i) { | ||
args[i] = arguments[i]; | ||
@@ -31,12 +41,13 @@ } | ||
} | ||
}; | ||
} | ||
if (self.cache.has(key)) { | ||
hitFn(null, self.cache.get(key)); | ||
return setImmediate(hitFn, null, self.cache.get(key)); | ||
} | ||
if (self.pending[key]) { | ||
self.pending[key].push(hitFn); | ||
} else { | ||
if (self.pending[key]) { | ||
self.pending[key].push(hitFn); | ||
} else { | ||
self.pending[key] = [hitFn]; | ||
resolveFn(resolvedCallback); | ||
} | ||
self.pending[key] = [hitFn]; | ||
resolveFn(resolvedCallback); | ||
} | ||
@@ -43,0 +54,0 @@ } |
{ | ||
"name": "exp-asynccache", | ||
"description": " A small async cache", | ||
"version": "1.0.0", | ||
"version": "1.1.0", | ||
"author": "AB Kvällstidningen Expressen", | ||
"contributors": [ | ||
"Anders Kindberg <ndrsbngtssn@yahoo.se>", | ||
"Gabriel Falkenberg <gabriel.falkenberg@gmail.com>", | ||
"Jens Carlén", | ||
"Joel Abrahamsson" | ||
], | ||
"scripts": { | ||
@@ -7,0 +13,0 @@ "test": "mocha --reporter spec" |
@@ -6,2 +6,5 @@ asynccache | ||
Errors are not cached and the callback function is always called asynchronously even if the value is resolved | ||
synchronously. | ||
Callback usage: | ||
@@ -55,1 +58,24 @@ | ||
``` | ||
## Warning | ||
Don't use more data from the closure than what is used to construct the cache key: | ||
```javascript | ||
var cache = new AsyncCache(); | ||
function getPerson(name, location, callback) { | ||
cache.lookup(name, function (resolve) { // <-- Only name is used | ||
personRepo.get(name, location, resolve); // <-- Both name and location is used | ||
}, callback); | ||
} | ||
``` | ||
In the above example there might be several different objects returned by personRepo for the same name but with | ||
different locations but they are all cached only by the name. The correct code would be to construct the cache key | ||
from both name and location. |
5499
25.35%56
14.29%80
48.15%