[英]How to specify resolution and rejection type of the promise in JSDoc?
我有一些代码返回一个promise对象,例如使用Node库的Q库。
var Q = require('q');
/**
* @returns ???
*/
function task(err) {
return err? Q.reject(new Error('Some error')) : Q.resolve('Some result');
}
如何使用JSDoc记录这样的返回值?
即使它们不存在于Javascript中,我发现JSdoc理解“泛型类型”。
因此,您可以定义自定义类型,然后使用/* @return Promise<MyType> */
。 以下结果是一个很好的TokenConsume(令牌)→{Promise。<Token>},其中包含指向doc中自定义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> */
。
我倾向于为承诺定义一个外部类型:
/**
* 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');
}
使用JSDoc,您还可以使用@typedef
创建自定义类型。 我使用这个相当多,所以使用字符串或数组的props / params链接到类型的描述(比如string
我创建了一个包含字符串可用的本机的typedef(参见下面的示例JSDoc)。您可以定义一个自定义以同样的方式输入。这是因为你不能像@property那样使用对象点表示法来表示返回中的内容。所以在你返回类似对象的东西的情况下,你可以创建一个该类型的定义(' @typedef MyObject
)然后@returns {myObject} Definition of myObject
。
不过,我不会对此感到沮丧,因为类型应该尽可能的文字并且您不想污染您的类型,但是有些情况下您需要明确定义类型,因此您可以记录什么是在它(一个很好的例子是Modernizr ...它返回一个对象,但你没有它的文档,所以创建一个自定义typedef,详细说明该返回的内容)。
如果你不需要走这条路,然后有人已经提到的,你可以为任何@param,@property指定多个类型,或通过管道返回: |
。
在您的情况下,您还应该记录@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
*/
即使它可能已被弃用,还有另一种方法可以做到这一点。 强调可能因为有人说它已被弃用(检查对该答案的评论),而其他人说任何一个都没问题。 为了完整起见,无论如何我都要报道。
现在,以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};
};
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
这是我喜欢做的事情(可能有点过头了):
/**
* @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解析或失败时调用的回调,然后定义链接回到的特定承诺。回调文档。
最后,使用您的特定承诺类型作为返回类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.