Skip to content

Instantly share code, notes, and snippets.

@mnutt
Last active May 15, 2019 19:52
Show Gist options
  • Save mnutt/d14432454e6f35a324070a4f1b9f649e to your computer and use it in GitHub Desktop.
Save mnutt/d14432454e6f35a324070a4f1b9f649e to your computer and use it in GitHub Desktop.
In-memory write-through cache with async/await
// before async/await
cache.oldThrough(cacheKey, function getData(cb) {
fetch(appUrl, function(response) {
response.text(function(data) {
cb(data);
});
});
}, function (template) {
res.end(template);
});
// with async/await
const template = await cache.through(cacheKey, async () => {
const response = await fetch(appUrl);
return response.text();
});
res.end(template);
// cache implementation
class Cache {
async through(key, fn) {
const cached = this.get(key);
if (cached) {
return cached;
}
if (this.inFlight(key)) {
return this.getLayer(key);
}
this.lock(key);
try {
const value = await fn();
this.set(key, value);
this.unlock(key, value);
return value;
} catch(e) {
this.abandon(key);
throw(e);
}
}
oldThrough(key, getData, cb) {
const cached = this.get(key);
if (cached) {
cb(cached);
} else if (this.inFlight(key)) {
this.getLater(key, function(value) {
cb(value);
});
} else {
this.lock(key);
getData((value) => {
this.set(key, value);
this.unlock(key, value);
cb(value)
});
}
}
get() {
...
}
...
}
const cache = new Cache(5000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment