var cache = {};
function getCache(key, dep) {
    if (cache[key] == undefined) {
        dep.call(null,function(err, list) {
            cache[key] = list;
        });
        return cache[key];
    } else {
        return cache[key];
    }
}
var data = getCache("aa",
function(cb) {
    BlogModel.find({}, cb);
   
});
console.log(data);
```
本来是根据key去cache中查找,如果找不到,就执行BlogModel查数据然后放在cache中,因为异步的原因返回是undefined,但如果在cb写在getCache调用的代码里,嵌套就太深了,而且代码都一样,看有没有更好的办法
      5 回复
    
    var cache = {};
function getCache(key, dep, callback) {
  if (!cache.hasOwnProperty(key)) {
    dep.call(null,function(err, list) {
      cache[key] = list;
      callback(null, list);
    });
  } else {
    callback(null, cache[key]);
  }
}
getCache("aa", function (cb) {
  BlogModel.find({}, cb);
}, function (err, data) {
  console.log(data);
});
var redis = require('redis');
var client = redis.createClient();
var cache = {}
cache.getKey = function(key, callback){
  client.get(key, callback);
};
cache.setKey = function(key, val, callback){
    client.set(key, val, function(err){
        callback(err, val);
    });
}
var getCache = function(key, dep, callback){
    cache.getKey(key, function(err, replies){
        if(err) return callback(err);
        if(!replies) {
            dep.call(null, function(err, val){
                if(err) return callback(err);
                cache.setKey(key, val, callback);
            });
        } else {
            return callback(err, replies);
        }
    });
}
getCache('aa', function(cb){
    cb(null, '123')
},function(err, data){
    console.log(data);
});
redis缓存版本
 
       
    