【问题标题】:Naming callbacks and Docblock in Javascript在 Javascript 中命名回调和 Docblock
【发布时间】:2016-09-07 04:40:12
【问题描述】:

当我编写代码时,让我(或其他人)清楚地了解正在发生的事情对我来说非常重要,这样我(或其他人)就不需要在以后浪费时间试图重新弄清楚所有事情。因此,我首先寻求有关回调命名约定的最佳实践。

此外,最近从 PHP (Symfony2) 切换并在我的 IDE 中使用 DocBlock 进行提示,我试图找出一种类似的方法来在我的 Javascript 代码中获得有用的提示。

例如:

# 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);
};

如果有人可以回答这些问题或将我链接到一些带有建议的好文档,那么我将非常感激。到目前为止,我发现这个很有帮助:

http://callbackhell.com/

但是像docblock callbacks 这样的搜索查询并没有提供任何有用的信息。

【问题讨论】:

  • 你应该使用承诺。
  • 这能回答所有问题吗?我有时使用async 库,但仍然有同样的问题。不过我还是很陌生

标签: javascript callback naming-conventions hint docblocks


【解决方案1】:

这可以帮助 JavaScript 中的 docblock https://devdocs.magento.com/guides/v2.4/coding-standards/docblock-standard-javascript.html

谈到回调命名约定的最佳实践我认为使用“on”前缀是一个不错的选择,例如onSuccessonFailure。看thisreddit cmets

【讨论】:

  • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接答案可能会失效。 - From Review
猜你喜欢
  • 2012-04-02
  • 2015-03-02
  • 2013-11-06
  • 1970-01-01
  • 2022-12-13
  • 2020-08-17
  • 2020-12-21
  • 2017-10-24
  • 1970-01-01
相关资源
最近更新 更多