【发布时间】:2012-06-13 00:18:09
【问题描述】:
我的文件已读入并被正确解析,但我似乎无法返回输出字符串。我希望能够从分配给客户端的变量中访问该字符串。我正在使用异步系列来帮助缓解回调地狱,并且输出可以很好地到达控制台。但是,如果我将返回输出放在同一个位置,它就不起作用。有什么建议吗?
embed_analytics: function(){
var output;
async.series({
read_file: function(callback){
fs.readFile(__rootpath+'/apps/analytics/data/analytics.json', 'UTF-8', function(err,data){
if(err) {
console.error("Could not open file: %s", err);
process.exit(1);
}
try {
var config = JSON.parse(data);
callback(null, config);
}
catch(exception) {
console.error("There was an error parsing the json config file: ", exception);
process.exit(1);
}
});
}
},
function(err, results) {
_.each(results.read_file, function(element){
output+="$('"+element.Selector+"').click(function(){_gaq.push(['_trackEvent',"+element.Category+","+element.Action+","+element.Label+"]);});\n";
});
console.log(output);
}
);
}
【问题讨论】:
-
自带异步域。这简直是不可能的。你必须给自己的 API 一个回调参数。
-
从未听说过
callback hell。也从未涉足。只有当您不切换到异步状态并继续尝试同步编程时,您才会进入它。 -
啊,今天学到了新东西。感谢大家的帮助。
标签: javascript node.js asynchronous express fs