Why can't I access the local variable in closure

107 views Asked by At

I have the following code. I save some data into the cache variable in the callback of the parallel, but inside the parallel the cache object is always empty. Any ideas?

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

There are 1 answers

0
Barış Uşaklı On BEST ANSWER

The problem was async.map it was calling loadTopicInfo in parallel for 20 topics. So the cache check was happening before anything was saved in the cache. DUH! Replacing it with async.eachSeries solved the problem.