I have the following code in my nodejs application:
function someFileOperation(callback) {
var files = ...;
files.forEach(function (file) {
doSomethingAsync(file, function (err, result) {
});
});
}
What is an elegant way to call the callback of someFileOperation() in case all doSomethingAsync() called their callback function and call it only once, when an error in doSomethingAsync() occurred?
For now I came up with something like this:
function someFileOperation(callback) {
var files = ...;
var noFiles = files.length;
files.forEach(function (file) {
doSomethingAsync(file, function (err, result) {
if (err) {
callback(err);
callback = function () {}; // I don't want it to be called again
} else if (--noFiles <= 0) {
callback(null, true);
}
});
});
}
But I think this is a lot of overhead for such a simple task. So I am looking for a much more elegant way or maybe a little framework for these kind of problems
Use async.map or async.foreach see here: https://github.com/caolan/async#map and https://github.com/caolan/async#forEach
the async.map method takes an array of items and performs the same async call for each item in your array in parallel. If no errors are encountered, it will call a callback with a new array of results.