Javascript 强制x客户机等待node.js中客户机y的回调的最佳实践
我正在尝试使用node.js为不同的客户端实现一个数据交付工具的缓存系统。 这是一个http服务,我使用express来处理请求。我的缓存系统需要支持三种情况: 案例1-没有缓存: 程序通过给定的get方法接收数据。如果成功,它将写入缓存 案例2-存在缓存: 程序接收缓存 案例3-没有缓存,但同一请求的get方法已被其他客户端调用,当前正在处理中。 程序需要等待,直到另一个请求通过get方法接收到它的数据并交付新写入的缓存Javascript 强制x客户机等待node.js中客户机y的回调的最佳实践,javascript,node.js,events,callback,queue,Javascript,Node.js,Events,Callback,Queue,我正在尝试使用node.js为不同的客户端实现一个数据交付工具的缓存系统。 这是一个http服务,我使用express来处理请求。我的缓存系统需要支持三种情况: 案例1-没有缓存: 程序通过给定的get方法接收数据。如果成功,它将写入缓存 案例2-存在缓存: 程序接收缓存 案例3-没有缓存,但同一请求的get方法已被其他客户端调用,当前正在处理中。 程序需要等待,直到另一个请求通过get方法接收到它的数据并交付新写入的缓存 我用事件解决了“案例3”的问题。我为每个客户机/请求组合注册一个事件。但
我用事件解决了“案例3”的问题。我为每个客户机/请求组合注册一个事件。但是,记录大量公开的事件感觉不是很优雅。此外,使用队列并不是最好的解决方案之一。在我看来,实现缓存系统不需要事件,但我不知道没有队列如何实现它 以下是我将如何实现缓存:
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); })
}
}
}
在我看来,您不需要事件来实现缓存系统,但我不知道如何在没有队列的情况下实现它 以下是我将如何实现缓存:
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); })
}
}
}