为什么我不能在闭包中访问局部variables
我有以下代码。 我将一些数据保存在并行的callback中的cachingvariables中,但在并行内部,caching对象总是空的。 有任何想法吗?
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
。 所以caching检查是在caching中保存任何内容之前进行的。 DUH! 用async.eachSeriesreplace它解决了这个问题。
- 是否有可能在Mongoose中定义一个default_scope?
- 无法将函数的结果传递给node.js中的全局作用域
- templateDatavariables返回未定义的帮助函数(docpad.coffeeconfiguration文件)
- JavaScript和Node.JS – 无法理解为什么variables在callback中是未定义的
- 节点的JS如何从一个函数的callback函数访问全局variables?
- 失去全球variables价值
- Node.js HTTPcallback中的“this”损失上下文
- 这是NodeJS中的一个variables范围问题,还是我需要更多的睡眠?
- Node.js和客户端共享相同的脚本