92

我有一些返回promise 对象的代码,例如使用NodeJS 的Q库。

var Q = require('q');

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

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

4

6 回答 6

93

即使它们在 Javascript 中不存在,我发现 JSdoc 理解“泛型类型”。

因此,您可以定义自定义类型,然后使用/* @return Promise<MyType> */. 以下结果生成了一个不错的TokenConsume(token) → {Promise.<Token>},其中包含指向文档中您的自定义Token类型的链接。

/**
 * @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
}

它甚至可以与/* @return Promise<MyType|Error> */or一起使用/* @return Promise<MyType, Error> */

于 2014-02-11T22:55:03.637 回答
7

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

/**
* A promise object provided by the q promise library.
* @external Promise
* @see {@link https://github.com/kriskowal/q/wiki/API-Reference}
*/

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

/**
* @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');
}
于 2013-11-20T11:02:14.890 回答
7

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() {
     // ...
};

以后支持吗?

/**
 * 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() {
    // ...
};

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

于 2017-10-13T15:27:02.767 回答
6

使用 JSDoc,您还可以使用@typedef. 我经常使用它,因此作为字符串或数组的 props/params 链接到类型的描述(例如,string我创建了一个 typedef,其中包括可用于字符串的原生对象(请参阅下面的示例 JSDoc)。您可以定义自定义类型以同样的方式。这是因为您不能像 @property 那样使用对象点表示法来表示返回值。因此,如果您要返回对象之类的东西,则可以创建一个定义对于该类型 (' @typedef MyObject),然后@returns {myObject} Definition of myObject.

不过,我不会为此发疯,因为类型应该尽可能字面化,并且您不想污染您的类型,但是在某些情况下您想显式定义类型,因此您可以记录什么是在其中(一个很好的例子是 Modernizr ......它返回一个对象,但是您没有它的文档,因此创建一个自定义 typedef 来详细说明该返回中的内容)。

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

在您的情况下,您还应该记录 an@throws因为您正在抛出一个new error* @throws {error}当属性 err 未定义或不可用时抛出一个真正的新错误事件。

//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
*/
于 2013-02-25T19:39:02.223 回答
5

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

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

{Promise.<Array.<*>>}

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

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

无论如何,如果您以以下功能为例:

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

    return {array1, array2};
};

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

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

    return {array1, array2};
};
于 2017-06-23T16:56:53.877 回答
0

这是我喜欢做的事情(可能有点过头了):

/**
 * @external Promise
 * @see {@link http://api.jquery.com/Types/#Promise Promise}
 */

/**
 * This callback is called when the result is loaded.
 *
 * @callback SuccessCallback
 * @param {string} result - The result is loaded.
 */

/**
 * This callback is called when the result fails to load.
 *
 * @callback ErrorCallback
 * @param {Error} error - The error that occurred while loading the result.
 */

/**
 * Resolves with a {@link SuccessCallback}, fails with a {@link ErrorCallback}
 *
 * @typedef {external:Promise} LoadResultPromise
 */

/**
 * Loads the result
 *
 * @returns {LoadResultPromise} The promise that the result will load.
 */
function loadResult() {
    // do something
    return promise;
}

基本上,使用指向某些文档的链接定义基本承诺(在这种情况下,我链接到 jQuery 的),定义当承诺解决或失败时将调用的回调,然后定义链接回的特定承诺回调文档。

最后,使用您的特定承诺类型作为返回类型。

于 2014-01-29T21:18:11.270 回答