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

时间:2012-10-27 21:37:47

标签: javascript node.js documentation jsdoc promise

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

var Q = require('q');

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

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

6 个答案:

答案 0 :(得分:44)

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

因此,您可以定义自定义类型,然后使用/* @return Promise<MyType> */。以下结果是一个很好的 TokenConsume(令牌)→{Promise。&lt; Token&gt;} ,其中包含指向文档中自定义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> *//* @return Promise<MyType, Error> */

答案 1 :(得分:7)

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

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

现在,您可以在函数文档的@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');
}

答案 2 :(得分: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
*/

答案 3 :(得分:3)

即使可能 已弃用,也有另一种方法可以做到这一点。强调可能,因为someone说它被弃用(检查对该答案的评论),而others说任何一个都没问题。为了完整起见,我还是要报告它。

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

{Promise.<Array.<*>>}

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

在撰写本文时,当我尝试使用 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};
};

答案 4 :(得分:3)

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

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

上的github讨论

答案 5 :(得分: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),定义将在promise解析或失败时调用的回调,然后定义您的特定承诺链接回到回调文档。

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