Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.