by jQueryIsAwesome · 13y ago · 0 comments
var result = [];
paths.forEach(function (i, file){
fs.stat(file, function (err, data){
result.push(data);
if (i === 0) {
// Use stat size
}
if (result.length === paths.length) {
// Use the stats
}
});
});
Fairly understandable, more efficient and without introducing logic patterns foreign to many. It also meet his requirements (It is parallel and we only hit every file once) 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);Consider your use of the forEach() abstraction when you could have used a for() loop just as easily. (That said, I agree the article in general could do a better job of describing the "other" side)
And in such case you would only do this once outside the listeners of http/or-whatever connections so it would be done just once regardless of the number of concurrent activity.
fs.statMany(filenames, function (stats) { ... });
or: var statsPromise = fs.statMany(filenames);
And then in either case, you'd just use a for-loop or forEach or whatever your preference on the result. No thinking about how to preserve complex invariants or whatever is necessary.Hell, with ES6 generator-y expressions you could make it even more succinct, something like:
var result;
fs.statMany(filenames, function (stats) { result = [... for x in stats]; });
No push nonsense, no nested if statements, no need to explicitly invoke async.parallel or whatever. Just clarity.Why don't we all just go back to manually pushing/popping arguments on the stack like in assembly language while we're at it?