0

When I am writing code, it is very important to me to make obvious what is happening so that I (or others) don't need to waste time later on trying to re-figure everything out. I am therefore firstly seeking best practices regarding naming conventions for callbacks.

Also, switching recently from PHP (Symfony2) and having used DocBlock for hinting within my IDE, I am trying to figure out a similar way to get useful hints within my Javascript code.

For example:

# app.js
# .. requires etc

// Question 1. Naming the function (`function importFinishedHandler (..`) makes it easier to debug (see callbackhell.com). But do I really need to assign this to a variable, as it seems to work without, is there any difference?
var importFinishedHandler = function importFinishedHandler (err, data) {
    # handle err or data
};

var importer = new Importer();
importer.import('../path/to/myfile.json', importFinishedHandler);



# importer.js

// Question 2. Is it good practice to name the `callback` here something descriptive such as `importFinishedHandler` (instead of just `callback` which is what I see a lot of people doing), as passed in from the `app.js` file.
// Question 3. When I want to see what parameters the `importFinishedHandler` callback function requires, I need to go back into `app.js` and check manually. In this instance it is pretty easy to see, but when files get big it isn't. Is there any way to use `Docblock` or something so that my IDE (WebStorm) can give me the correct required parameters?
Importer.prototype.import = function (file, importFinishedHandler) {
    # do import stuff
    importFinishedHandler(null, data);
};

If anyone could answer these questions or link me to some good documentation with suggestions, then I would be very grateful. I have found this one so far which has been helpful:

http://callbackhell.com/

But search queries such as docblock callbacks aren't coming up with anything useful.

timhc22
  • 7,213
  • 8
  • 48
  • 66

1 Answers1

0

This could help with docblock in JavaScript https://devdocs.magento.com/guides/v2.4/coding-standards/docblock-standard-javascript.html

Speaking of best practices for callback naming convention I think using "on" prefix is a good one e.g onSuccess, onFailure. look at this reddit comments

Stanley
  • 89
  • 8
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/30161474) – kian Oct 24 '21 at 07:21