|
|
|
|
|
by asolove
4824 days ago
|
|
To be fair, you haven't handled the complete case. What if one of the items fails? You need to handle the error, but only if it's the first error, and make sure to tell all later-called callbacks that they're too late and we have already failed. Except, if we got an error on an early callback but the 0th item comes back later, we need to do whatever we were going to do with that one piece of data. 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?
So you don't need to copy around a variable called "hasFail", one line can be enough