我有以下代码。我在并行回调中将一些数据保存到缓存变量中,但在并行内部缓存对象始终为空。有什么想法吗?
Topics.getTopicsByTids = function(tids, uid, callback) {
var cache = {};
function loadTopicInfo(topicData, next) {
async.parallel({
privileges: function(next) {
console.log(cache); // always prints empty object
if (cache[topicData.cid]) {
console.log('CACHE');
return next(null, cache[topicData.cid])
}
categoryTools.privileges(topicData.cid, uid, next);
}
}, function(err, topicInfo) {
// save privs to cache, doesnt seem to modify
//the cache object in the outer scope
cache[topicData.cid] = topicInfo.privileges;
console.log(cache); // prints out the cached data
next(null, topicData);
});
}
Topics.getTopicsData(tids, function(err, topics) {
async.map(topics, loadTopicInfo, callback);
});
};
最佳答案
问题是 async.map
它正在为 20 个主题并行调用 loadTopicInfo
。因此,缓存检查发生在缓存中保存任何内容之前。呸!用 async.eachSeries 替换它解决了这个问题。
关于javascript - 为什么我不能在闭包中访问局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22278270/