Hacker News new | ask | show | jobs
by ehsanul 5553 days ago
I must be missing something, but how is EventEmitter helping you get rid of the nested code in your examples? It looks like changing all the anonymous callbacks to named functions, and then using the function names as the callbacks is what made the code more readable. EventEmitter wasn't necessary to do that, right?
1 comments

Yes and no -- it's not absolutely necessary; I could've written it similarly without turning the callback-accepting functions into emitter-returning functions. It would have felt gross to do so, though. The downside I see with using straight callbacks that accept error and data arguments is that they conflate the logic of what that callback is actually attempting to do with the error-checking of the calling function. For example, my `baseDirOkay` method shouldn't care whether or not the calling `fs.stat` function succeeded or failed -- it should only care that the data it was passed is or isn't a directory. It shouldn't be called at all if the path was not valid. With an EventEmitter api, I can rely on the emitter itself to tell me whether or not to even call my `baseDirOkay` function, instead of having to conflate that logic with my method.

This seems like a tiny gain in readability, but it means that I don't have to make a decision between putting the error/success logic of `fs.readFile` in my method (where it does not go) and my calling function (where it probably does not go, and where it would incur unnecessary nesting -- and the finagling of the `this` variable that that incurs).

This may just be my taste -- but I find designing around (and reasoning about) EventEmitter-type API's much easier.