by asolove · 13y ago · 0 comments
var result = [];
var hasFailed = false;
paths.forEach(function (i, file){
fs.stat(file, function (err, data){
// if previous callback failed, give up.
// unless this is the first item, which we still need
if(hasFailed && i !== 0) return;
if(err) {
hasFailed = true;
// do something with the error
if (i === 0) // do something special for error on first item.
return;
}
result.push(data);
if (i === 0) {
// Use stat size
// remember we might have already failed, in which case don't add the first item to the general result
if(hasFailed) return;
}
if (result.length === paths.length) {
// Use the stats
}
});
});
That's almost certainly still not close to right. Which just illustrates the basic problem: without either promises or something like async.js, you're reimplementing control flow by yourself. You can easily start with perfectly-nice-looking code that balloons to be incomprehensible as soon as you start caring about error cases. And where two statements, perhaps dozens of lines apart, are preserving some invariant that is not obvious to someone editing your code in the future. Even yourself.And your example is disingenuous too, why do we need to add so much logic instead of collecting the errors if you want to handle them anyway?
result.push(err || data);
So you don't need to copy around a variable called "hasFail", one line can be enough var failed = results.every(Buffer.isBuffer);