简体   繁体   English

来自JavaScript中的匿名回调的冗余JSDoc @return

[英]Redundant JSDoc @return from an anonymous callback in JavaScript

I am using JSCS with Google preset style rules to check my code and I have a method in a DAO class defined like so: 我正在使用带有Google预设样式规则的JSCS来检查我的代码,并且我在DAO类中定义了一个方法,如下所示:

/**
 * Inserts a new user into database.
 *
 * @param {User} user User to insert.
 * @return {User} Last inserted user.  // Redundant return statement
 * @throws Error if query fails.
 * @since 1.0
 */
add(user) {
  this.pool.getConnection((err, conn) => {
    conn.query('INSERT INTO users SET ?', user, (err, rows) => {
      if (err) {
        throw err;
      }
      conn.release();
      return this.getById(rows.insertId);
    });
  });
}

JSCS marks JSDoc @return tag as redundant because it can't find a return statement inside add(user) function scope, but it actually resides inside the anonymous callback (err, rows) => { ... } . JSCS将JSDoc @return标记标记为冗余,因为它无法在add(user)函数范围内找到return语句,但它实际上位于匿名回调(err, rows) => { ... }

How can I correctly document that return statement? 如何正确记录该退货声明? Is my approach wrong or bad in some way? 我的方法在某种程度上是错误的还是坏的?

add does not return anything, so JSDoc is correct when it tells you that your @return tag is not appropriate. add不会返回任何内容,因此当JSDoc告诉您@return标记不合适时,它是正确的。 If you refactored your code so that add accepted a callback which is passed the result (as described in How do I return the response from an asynchronous call? ), you would end up with 如果你重构你的代码,以便add接受一个传递结果的回调(如我如何从异步调用返回响应中所述? ),你最终会得到

add(user, resultCallback) {
  this.pool.getConnection((err, conn) => {
    conn.query('INSERT INTO users SET ?', user, (err, rows) => {
      if (err) {
        throw err;
      }
      conn.release();
      resultCallback(this.getById(rows.insertId));
    });
  });
}

Call this with add(user, result => { ... }) instead of result = add(user) . add(user, result => { ... })而不是result = add(user)来调用它。

How to document this? 如何记录? See How to document callbacks using JSDoc? 请参阅如何使用JSDoc记录回调? It would look like: 它看起来像:

/**
 * Inserts a new user into database.
 *
 * @param {User} user User to insert.
 * @param {userResultCallback} resultCallback callback with last inserted user
 * @throws Error if query fails.
 * @since 1.0
*/
add(user, resultCallback) {
  //...
}

/**
 * Callback used to get a single User value.
 * @callback userResultCallback
 * @param {User} user Result of the callback
 */

The @callback at the bottom is stand-alone. 底部的@callback是独立的。 It defines a type of callback function, which in this case is a callback that accepts a User as its only argument. 它定义了一种回调函数,在这种情况下,它是一个接受User作为其唯一参数的回调。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM