Thanks in advance for taking a look at this.
I've got an async task within a loop that's not working. I've made sure to:
This function outputs... nothing!? For some reason the grunt.log.writeln statements aren't even firing. Task completes without errors. I also tried adding a 20-second delay, in case the script was finishing before the async task were returned. Oddly, if I don't call "done(error)," the files are written to file (when I replace the writeln's with grunt.file.write statements).
var done = this.async(),
exec = require('child_process').exec,
myJSON = {
"file1" : "C:/home/me/jquery.js",
"file2 " : "C:/home/me/grunt.js",
...
"fileN" : "C:/home/me/N.js"
},
count;
for (var key in myJSON) {
if (myJSON.hasOwnProperty(key)) {
(function (key) {
exec( 'type "' + myJSON[key] + '"',
function(error, stdout, stderr) {
if (error) {
grunt.log.writeln('!!! exec error: ' + error);
}
grunt.log.writeln('stdout: ' + stdout);
grunt.log.writeln('stderr: ' + stderr);
done(error);
}
);
})(key);
count++;
}
}
References:
http://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback https://github.com/gruntjs/grunt/wiki/Frequently-Asked-Questions
done()
should only be called when the whole operation is complete, which means when all the exec()
methods has run their callbacks. Currently you're executing the done
callback on each iteration. You can easily achieve this by using the forEach
method in the node module async which comes with grunt (grunt.util.async
(, or forEachSeries
if you want the exec()
methods executed in order.
Something like this (not tested):
var done = this.async();
var exec = require('child_process').exec;
var async = grunt.util.async; // updated
var myJSON = {
"file1": "C:/home/me/jquery.js",
"file2": "C:/home/me/grunt.js",
...
"fileN": "C:/home/me/N.js"
};
async.forEach(Object.keys(myJSON), function(el, cb) {
exec('type "' + myJSON[el] + '"', function(error, stdout, stderr) {
if (error) {
grunt.warn('!!! exec error: ' + error)
return cb(error);
}
grunt.log.writeln('stdout: ' + stdout);
grunt.log.writeln('stderr: ' + stderr);
cb();
}
);
}, function(error) {
done(!error);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With