如何在JSDoc中指定promise的解析和拒绝类型?

Ari*_*kon 70 javascript documentation node.js promise jsdoc

我有一些代码返回一个promise对象,例如使用Node库的Q库.

var Q = require('q');

/**
 * @returns ???
 */
function task(err) {
    return err? Q.reject(new Error('Some error')) : Q.resolve('Some result');
}
Run Code Online (Sandbox Code Playgroud)

如何使用JSDoc记录这样的返回值?

jil*_*lro 58

即使它们不存在于Javascript中,我发现JSdoc理解"泛型类型".

因此,您可以定义自定义类型然后使用/* @return Promise<MyType> */.以下结果是一个很好的TokenConsume(令牌)→{Promise.<Token>},其中包含指向Tokendoc中自定义类型的链接.

/**
 * @typedef Token
 * @property {bool} valid True if the token is valid.
 * @property {string} id The user id bound to the token.
 */

/**
 * Consume a token
 * @param  {string} token [description]
 * @return {Promise<Token>} A promise to the token.
 */
TokenConsume = function (string) {
  // bla bla
}
Run Code Online (Sandbox Code Playgroud)

它甚至适用于/* @return Promise<MyType|Error> *//* @return Promise<MyType, Error> */.

  • 项目所有者关于当前解决方案以及计划发布的内容的更新https://github.com/jsdoc3/jsdoc/issues/1197#issuecomment-312948746 (2认同)

mir*_*ula 7

我倾向于为承诺定义一个外部类型:

/**
* A promise object provided by the q promise library.
* @external Promise
* @see {@link https://github.com/kriskowal/q/wiki/API-Reference}
*/
Run Code Online (Sandbox Code Playgroud)

现在,您可以在@return函数文档的声明中描述承诺会发生什么:

/**
* @return {external:Promise}  On success the promise will be resolved with 
* "some result".<br>
* On error the promise will be rejected with an {@link Error}.
*/
function task(err) {
    return err? Q.reject(new Error('Some error')) : Q.resolve('Some result');
}
Run Code Online (Sandbox Code Playgroud)


小智 6

使用JSDoc,您还可以使用创建自定义类型@typedef.我使用这个相当多,所以使用字符串或数组的props/params链接到类型的描述(比如string我创建了一个包含字符串可用的本机的typedef(参见下面的示例JSDoc).您可以定义自定义类型这样做是因为你不能像@property那样使用对象点表示法来表示返回中的内容.所以在你返回像对象这样的东西的情况下,你可以创建一个定义对于那种类型(' @typedef MyObject)然后@returns {myObject} Definition of myObject.

不过,我不会对此感到沮丧,因为类型应该尽可能的文字并且您不想污染您的类型,但是有些情况下您需要明确定义类型,因此您可以记录什么是在它(一个很好的例子是Modernizr ...它返回一个对象,但你没有它的文档,所以创建一个自定义typedef,详细说明该返回的内容).

如果您不需要走这条路线,那么就像已经提到的那样,您可以使用管道为任何@ param,@ property或@return指定多种类型|.

在你的情况下,你也应该记录一个,@throws因为你扔了new error:* @throws {error} Throws a true new error event when the property err is undefined or not available.

//saved in a file named typedefs.jsdoc, that is in your jsdoc crawl path
/**
    * @typedef string
    * @author me
    * @description A string literal takes form in a sequence of any valid characters. The `string` type is not the same as `string object`.
    * @property {number} length The length of the string
    * @property {number} indexOf The occurence (number of characters in from the start of the string) where a specifc character occurs
    * @property {number} lastIndexOf The last occurence (number of characters in from the end of the string) where a specifc character occurs
    * @property {string|number} charAt Gives the character that occurs in a specific part of the string
    * @property {array} split Allows a string to be split on characters, such as `myString.split(' ')` will split the string into an array on blank spaces
    * @property {string} toLowerCase Transfer a string to be all lower case
    * @property {string} toUpperCase Transfer a string to be all upper case
    * @property {string} substring Used to take a part of a string from a given range, such as `myString.substring(0,5)` will return the first 6 characters
    * @property {string} substr Simialr to `substring`, `substr` uses a starting point, and then the number of characters to continue the range. `mystring.substr(2,8)` will return the characters starting at character 2 and conitnuing on for 8 more characters
    * @example var myString = 'this is my string, there are many like it but this one is HOT!';
    * @example
    //This example uses the string object to create a string...this is almost never needed
    myString = new String('my string');
    myEasierString = 'my string';//exactly the same as what the line above is doing
*/
Run Code Online (Sandbox Code Playgroud)


hol*_*erd 6

Jsdoc3 目前支持的语法:

/**
 * Retrieve the user's favorite color.
 *
 * @returns {Promise<string>} A promise that contains the user's favorite color
 * when fulfilled.
 */
User.prototype.getFavoriteColor = function() {
     // ...
};
Run Code Online (Sandbox Code Playgroud)

未来是否支持?

/**
 * A promise for the user's favorite color.
 *
 * @promise FavoriteColorPromise
 * @fulfill {string} The user's favorite color.
 * @reject {TypeError} The user's favorite color is an invalid type.
 * @reject {MissingColorError} The user has not specified a favorite color.
 */

/**
 * Retrieve the user's favorite color.
 *
 * @returns {FavoriteColorPromise} A promise for the user's favorite color.
 */
User.prototype.getFavoriteColor = function() {
    // ...
};
Run Code Online (Sandbox Code Playgroud)

参见 github 讨论:https : //github.com/jsdoc3/jsdoc/issues/1197


Fra*_*ula 5

还有另一种方法可以做到这一点,即使它可能DEPRECATED。强调可能,因为有人说它已被弃用(检查对该答案的评论),而其他人则说任何一个都可以。为了完整起见,我无论如何都要报告它。

现在,以Promise.all()返回一个用数组实现的 Promise 为例。使用点符号样式,它看起来如下所示:

{Promise.<Array.<*>>}
Run Code Online (Sandbox Code Playgroud)

它适用于 JetBrains 产品(例如 PhpStorm、WebStorm),也用于jsforce 文档

在撰写本文时,当我尝试使用PHPStorm自动生成一些文档时,它默认为这种样式,即使我发现对它的引用不佳。

无论如何,如果您以以下函数为例:

// NOTE: async functions always return a Promise
const test = async () => { 
    let array1 = [], array2 = [];

    return {array1, array2};
};
Run Code Online (Sandbox Code Playgroud)

当我让PhpStorm生成文档时,我得到了这个:

/**
 * @returns {Promise.<{array1: Array, array2: Array}>}
 */
const test = async () => {
    let array1 = [], array2 = [];

    return {array1, array2};
};
Run Code Online (Sandbox Code Playgroud)