3 ms·
Please stop spreading FUD. With promises (Bluebird) this sounds like very little code in practice, assuming promisifyAll has been called the FS module: - One
by inglor 13y ago
Please stop spreading FUD.
With promises (Bluebird) this sounds like very little code in practice, assuming promisifyAll has been called the FS module:
- One line to read all files in a directory
- Map them with .map to a .stat call on them, returning array of promises.
- Reduce them to the largest element.
Something like:
var fs = Promise.promisifyAll(require("fs"));
var largest = fs.readdirAsync("/your/file/path").map(function(file){
return fs.statAsync(file);
}).reduce(function(x,y){
return (x.size > y.size) ? x : y;
});
With arrow syntax:
var largest = fs.readdirAsync("/your/file/path").
map((file) => fs.statAsync(file)).
reduce((x,y) => (x.size > y.size) ? x : y);
Alternatively, with Generators using Bluebird promises
var largest = Promise.coroutine(function *largest(dirname){
var files = yield fs.readdirAsync(dirname);
var sizes = yield files.map(name => fs.statAsync(name));
return files.reduce((x,y) => x.size > y.size ? x : y);
});
If one error occurs, the promise rejects. VERY far from 27 lines of code. Not to mention you can of course compose these in one line if you extract them to methods like in your code:
var largest = fs.readdirAsync("/your/file/path").map(fs.statAsync).reduce(largest);
- rdtsc 13y ago> Please stop spreading FUD. Was that addressed to strongloop.com? They are the ones that posted an example with promises using 27+/-whitespace lines of code and the initial problem algorithm only had 4 lines. Sounds like you should write a blog post and not them about using promises. I don't use Node.js on daily basis and am not familiar with promises so just commented as an outsider based on the article. Your last one line looks fantastic and makes it clear what is going on. Any reason you can think of why that wasn't the "obvious" solution to the original posters of the article?
- inglor 13y agortdsc: > Was that addressed to strongloop.com? They are the ones that posted an example with promises using 27+/-whitespace lines of code and the initial problem algorithm only had 4 lines. Oh wow, this is my fault, I didn't read what they did there. I have __no idea__ why it took them 27 lines to implement this. It's rather trivial with promises. - They have a .then followed by a .map there causing nesting for no reason whatsoever. - They also get the file name, but handle this very poorly (with an array), where they could just do it as a part of the .map (the .all and .then are completely redundant) there - They assume the possibility of directories, I didn't. That .filter is justified but that's the only thing one might have to add here. - Generally, it's poor promise code. I guess that promises are just not their tools of choice and they just used them _for that post_.
- deleted 13y ago[deleted]