Last active
May 15, 2019 19:52
-
-
Save mnutt/d14432454e6f35a324070a4f1b9f649e to your computer and use it in GitHub Desktop.
In-memory write-through cache with async/await
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// before async/await | |
cache.oldThrough(cacheKey, function getData(cb) { | |
fetch(appUrl, function(response) { | |
response.text(function(data) { | |
cb(data); | |
}); | |
}); | |
}, function (template) { | |
res.end(template); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// with async/await | |
const template = await cache.through(cacheKey, async () => { | |
const response = await fetch(appUrl); | |
return response.text(); | |
}); | |
res.end(template); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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