为什么我不能在闭包中访问局部变量

时间:2014-03-09 04:08:06

标签: javascript node.js scope

我有以下代码。我将一些数据保存到并行回调中的缓存变量中,但在并行内部,缓存对象始终为空。有什么想法吗?

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

1 个答案:

答案 0 :(得分:1)

问题是async.map它正在为20个主题并行调用loadTopicInfo。因此,在缓存中保存任何内容之前,都会进行缓存检查。 DUH!用async.eachSeries替换它解决了这个问题。