Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

When writing JavaScript (especially in node.js), I tend to use plain functions a

ID: 647844 • Letter: W

Question

When writing JavaScript (especially in node.js), I tend to use plain functions and callbacks. However, sometimes there's some context to share between some functions and I don't like to pass this context around every function in the chain. I usually create a "class" (I actually write in CoffeeScript, where the word class makes more sense), where the context is binded to this, while methods are still asynchronous - with callbacks. I hear voices that having classes and callbacks in one sentence is a smell, but I don't think it is - classes are just a syntax sugar for keeping context somewhere else than in function parameters.

What are advantages and/or disadvantages of both approaches? Is there a best practice?

Explanation / Answer

There's nothing inherently wrong with classes that have asynchronous methods. That's just part of the class's interface. Forget best practice for a moment, take a good look at the code, and ask yourself a question.

All other factors being equal, does turning the context object into a class make the code easier to read/understand?

If yes, then keep it. If no, then revert back to your original code and ask yourself why it wasn't easier to read/understand.

You may also want to consider alternate approaches to handling asynchronous control flow, such as Promises.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote