I have my file reading in and being parsed properly but I can't seem to return the string of output. I would like to be able to access this string from a variable that it gets assigned to on the client. I'm using async series to help alleviate callback hell and the output hits the console fine. However if I drop return output in that same spot it doesn't work. Suggestions?
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);
}
);
}
return
ing from an asynchronous function, like the callback for async.series
, doesn't mean anything. You'll need to pass a callback into the main function, and call it with output
:
embed_analytics: function(final_callback){
...
},
function(err, results) {
_.each(results.read_file, function(element){
output+="$('"+element.Selector+"').click(function(){_gaq.push(['_trackEvent',"+element.Category+","+element.Action+","+element.Label+"]);});\n";
});
final_callback(output);
}
);
}
And then use it as you would any other async function:
embed_analytics(function(data) {
// do something with data
});
It's asynchronous, you CANNOT return something from an asynchronous function. You must accept a callback that gets called when the operation is complete. Brandon Tilley has the correct code to do that.