如何在JSDoc中指定承诺的parsing和拒绝types?
我有一些代码返回一个承诺对象,例如使用Q库的NodeJS。
var Q = require('q'); /** * @returns ??? */ function task(err) { return err? Q.reject(new Error('Some error')) : Q.resolve('Some result'); }
如何使用JSDoc文档这样的返回值?
即使它们不存在于JavaScript中,我也发现JSdoc理解“generics”。
所以你可以定义你的自定义types,然后使用/* @return Promise<MyType> */
。 下面的结果是一个很好的TokenConsume(令牌)→{Promise。<Token>},它带有一个指向你的自定义Token
types的链接。
/** * @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> */
。
我倾向于为承诺定义一个外部types:
/** * 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'); }
使用JSDoc,您也可以使用@typedef
创build自定义types。 我使用这个相当多的东西,所以道具/参数是string或数组链接到types的描述(如string
我创build了一个typedef,其中包括可用于string的本机(见下面的示例JSDoc)您可以定义一个自定义因为你不能像@property一样使用对象点符号来表示返回值,所以在你返回类似对象的东西的时候,你可以创build一个该types的定义(' @typedef MyObject
),然后@returns {myObject} Definition of myObject
。
尽pipe如此,我不会为此而疯狂,因为types应该尽可能的符合字面意思,而且你不想污染你的types,但是有些情况下你想明确地定义types,所以你可以logging什么是(一个很好的例子是Modernizr …它返回一个对象,但是你没有它的文档,所以创build一个自定义的typedef来详细说明返回的内容)。
如果你不需要走这条路线,那么就像已经提到的那样,你可以通过使用pipe道指定多个@param,@property或@returntypes。 。
在你的情况下,你还应该logging一个@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 */
我相信接受的答案是缺less一个.
在Promise
这个词之后。
以Promise.all()
为例,它返回另一个用数组实现的Promise:
{Promise.<Array.<*>>}
引用jsforce文档 Promise.all()
返回一个包含每个promise的履行值的数组的promise 。
不要相信jsforce? 然后相信JetBrains =)
尝试写这个代码,让PHPStorm或WebStorm为你创buildJSDoc:
// NOTE: async functions always return a Promise const test = async () => { let array1 = [], array2 = []; return {array1, array2}; };
现在让PHPStorm或WebStorm创buildJSDoc和tada!
/** * @returns {Promise.<{array1: Array, array2: Array}>} */ const test = async () => { let array1 = [], array2 = []; return {array1, array2}; };
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讨论
这是我喜欢做的(可能有点过头了):
/** * @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之一),定义您的callback将被调用,当承诺要么解决或失败,然后定义您的具体承诺链接回到callback文档。
最后,使用您的特定承诺types作为返回types。