I'm building a function that will automatically scan a folder on server start or on folder change. The script will assemble a widgets folder for installed widgets, then concatenate and build a new partial file for inclusion in the front end app.
The script looks like:
concat.readMethodContents = function(concat) {
var widget;
for (widget in concat.widgets) {
var method;
for (method in concat.widgets[widget]) {
if (concat.widgets[widget][method].ready) {
concat.widgets[widget][method].ready = false;
fs.readFile('./lib/widgets/' + widget + '/methods/' + concat.widgets[widget][method].handle, 'utf8', function(err, data) {
if (err) {
console.log(err);
} else {
concat.widgets[widget][method].contents = data;
concat.writeJsPartialFile(concat);
}
});
}
}
}
}
Before this method is called, the concat object looks like:
{
"widgets": {
"hello_world": [{
"handle": "method1.js",
"ready": true
}, {
"handle": "method2.js",
"ready": true
}, {
"handle": "method3.js",
"ready": true
}]
}
}
The problem with the script is that when method is called, it is defined as done because the loop has finished and the async function is running a callback.
How can I encapsulate or otherwise preserve the variable through that part of the operation?