【问题标题】:Why can't I access the local variable in closure为什么我不能在闭包中访问局部变量
【发布时间】:2014-04-12 06:19:45
【问题描述】:

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

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

【问题讨论】:

    标签: javascript node.js scope


    【解决方案1】:

    问题是 async.map 它同时为 20 个主题调用 loadTopicInfo。因此,缓存检查是在缓存中保存任何内容之前进行的。呃!将其替换为 async.eachSeries 即可解决问题。

    【讨论】: