Loading...
const cache = new Map();
function getUser(id) {
return cache.getOrInsert(id, loadUser(id));
}const cache = new Map();
function getUser(id) {
return cache.getOrInsertComputed(id, (key) => loadUser(key));
}The callback runs only for missing keys, so loadUser() is no longer called on every cache hit.
getOrInsert() with an expensive default, which is created on every call.getOrInsertComputed(), so they are built only for missing keys.has(), set(), get() sequence for the same key.getOrInsertComputed() callback receive?It receives the key as its only argument, so map.getOrInsertComputed(id, loadUser) passes id to loadUser.
getOrInsertComputed() callback be async?Yes, but the Map then stores the returned promise, not the resolved value. That is a valid way to share one in-flight request per key.