IMO你不需要事件來實現你的緩存系統,但我沒有看到它如何實現沒有隊列。
這是我將如何實現緩存:
var cache = {};
function get(uri, cb) {
var key = uri; // id of the resource, you might want to strip some URI parts
var cacheEntry = cache[key];
if (!cacheEntry)
cache[key] = cacheEntry = {};
if (cacheEntry.value) {
// cache hit - return the cached value
return process.nextTick(function() { cb(null, cacheEntry.value });
}
if (cacheEntry.waiting) {
// another request is in progress - queue the callback
cacheEntry.waiting.push(cb);
return;
}
// we are the first client asking for this value
cacheEntry.waiting = [cb];
request.get(uri, handleResponse);
function handleResponse(err, resp, body) {
// process the response headers and body and save it to the cache
var content = body;
cacheEntry.value = content;
// fire callbacks waiting for the cached value
if (cacheEntry.waiting) {
var q = cacheEntry.waiting;
delete cacheEntry.waiting;
q.forEach(function(cb) { cb(null, content); })
}
}
}