3 ms·
I really appreciate the spirit of this, but this was super-light and I was hoping to see a few more fairly common idioms. I also take issue with a few points, a
by notduncansmith 12y ago
I really appreciate the spirit of this, but this was super-light and I was hoping to see a few more fairly common idioms. I also take issue with a few points, addressed below. His note about logic not going in app.js is one that I wish more Node developers I worked with would pay attention to: the first Node project I was thrown on at my current shop, app.js was about 2k LOC (things have gotten much better since then).
Some I would add:
- Prefer === over ==
- Prefer pure functions whenever possible
- Use promises, not callbacks. Wrap callbacks with promises when necessary. Do this once, and put that in a module.
- *Learn to use Lodash.* I've seen so many wheels reinvented you'd think I worked at Firestone.
- *Learn the rest of the ecosystem.* See above.
- Logic shouldn't go in route handlers. Routes should only orchestrate.
- Learn to love the Array functions. ForEach, Map, Reduce, Filter: use them.
I also have some beef with the article's content.
> [...] as a rule on thumb, I always use callbacks for any function, regardless of what it does.
Please don't. Callbacks are a (somewhat - see below) necessary evil, not an idiomatic good. Only use this if what you're doing is actually asynchronous - talking to the network, reading from the disk, making DB calls, etc. Maybe for really computationally expensive stuff (see bcrypt), but in day-to-day web dev you just won't run into that.
> If I know I'm going to be nesting callbacks more than two levels, I'll switch over to a package like async or write my own function quene method to help me out.
No. Do not do that. If you know you're going to be nesting callbacks more than 2 levels deep, just use the async package. Better yet, use promises from the beginning and don't worry about it.
> I know I've already made some people angry, and I'm okay with that.
You shouldn't be. If you've made anyone angry, it's because you're putting bad advice out there. Worse, it's mixed in with some really good advice, making it all the more deceptive.
Once again, I really appreciate the spirit in which this article was written. I just wish it wasn't mixing utter nonsense into otherwise sound advice.
- gcr 12y agoWhy is this bad advice? You haven't quantified any of your points, so I'm not sure whether there's any merit to either side.
- notduncansmith 12y agoWell, I feel like I explained why not to use callbacks everywhere (worth restating: it leads to unnecessarily messy code). As for why writing your own shoddy implementation of the async package, do I really have to explain why reinventing the wheel is a bad idea? If I did it would border on the hypocritical.