强制x客户端等待node.js中客户端y的callback的最佳实践

我正在尝试为node.js的不同客户端实现一个数据交付工具的caching系统。 这是一个http服务,我用快递处理请求。 我的caching系统需要支持三种情况:

案例1 – 没有caching:程序通过给定的get方法接收数据。 如果成功,则写入caching。

情况2 – 有一个caching:程序接收caching。

情况3 – 没有caching,但是相同请求的get方法已经被不同的客户端调用并且正在被处理。 程序需要等待另一个请求通过get方法接收到它的数据,并传递新写入的caching。

我用事件解决了“情况3”的问题。 我为每个客户/请求组合注册一个事件。 但是注册一个开放的事件感觉不是很优雅。 排队的使用也不是最好的解决scheme之一。

国际海事组织你不需要事件来实现你的caching系统,但我不知道如何实现没有队列。

这里是我将如何实现caching:

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); }) } } }