How to specify resolution and type of promise rejection in JSDoc?

I have code that returns a promise object, for example. using the Q library for NodeJS.

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

How to document such a return value using JSDoc?

+52
javascript promise documentation jsdoc
Oct 27
source share
6 answers

Even if they do not exist in Javascript, I found that JSdoc understands "generic types".

So you can define your custom types and then use /* @return Promise<MyType> */ . The following result in a good TokenConsume (token) -> {Promise. <Token>} with a link to your own Token type in the document.

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

It even works with /* @return Promise<MyType|Error> */ or /* @return Promise<MyType, Error> */ .

+34
Feb 11 '14 at 22:55
source share

I tend to define an external type for a promise:

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

Now you can describe in the @return statement your functional documentation what happens with the 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'); } 
+7
Nov 20 '13 at 11:02
source share

With JSDoc, you can also create your own types with @typedef . I use this quite a bit, so the details / parameters, which are strings or arrays, refer to the type description (for example, for string I created a typedef that includes the natives available for the string (see the JSDoc example below). A custom type like this This is due to the fact that you cannot use object point notation for returns, as you can for @property to denote what is in the opposite. Therefore, in cases when you return something like an object, you can create a definition for this type (' @typedef MyObject ) and then @returns {myObject} Definition of myObject .

I wouldnโ€™t be crazy about this because types should be as literal as possible and you donโ€™t want to pollute your types, but there are times when you want to explicitly define a type and you can document what is in it (a good example is Modernizr ... it returns an object, but you don't have documentation on it, so create a custom typedef that details what is in that return).

If you do not need to follow this route, then, as already mentioned, you can specify several types for any @param, @property or @return using the tube | .

In your case, you should also document @throws , because you are throwing 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 */ 
+6
Feb 25 '13 at 19:39
source share

There is another way to do this, even if it can be DEPRECATED . The emphasis is on maybe , because someone says that he is out of date (check the comments for this answer), while others say that one of them is in order. I am reporting this in any case for the sake of completeness.

Now take Promise.all() , for example, which returns a Promise executed with an array. Using the dot notation style, it will look like this:

 {Promise.<Array.<*>>} 

It works with JetBrains products (e.g. PhpStorm, WebStorm), and is also used in jsforce docs .

At the time of writing, when I try to auto-generate some documents using PHPStorm, it defaults to this style, although I found a bad link to it.

In any case, if you take the following function as an example:

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

When I let PhpStorm generate documents, I get the following:

 /** * @returns {Promise.<{array1: Array, array2: Array}>} */ const test = async () => { let array1 = [], array2 = []; return {array1, array2}; }; 
+2
Jun 23 '17 at 16:56 on
source share

The syntax currently supported by Jsdoc3 is:

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

Supported in the future?

 /** * A promise for the user favorite color. * * @promise FavoriteColorPromise * @fulfill {string} The user favorite color. * @reject {TypeError} The user favorite color is an invalid type. * @reject {MissingColorError} The user has not specified a favorite color. */ /** * Retrieve the user favorite color. * * @returns {FavoriteColorPromise} A promise for the user favorite color. */ User.prototype.getFavoriteColor = function() { // ... }; 

See the github discussion at: https://github.com/jsdoc3/jsdoc/issues/1197

+2
Oct 13 '17 at 15:27
source share

Here's what I like to do (which can go a little too far):

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

Basically, define a base promise with reference to some documentation (in this case I am contacting jQuery), define your callbacks that will be called when the promise is resolved or not fulfilled, then define your specific promise that links back to the return documentation call.

Finally, use the type of your promise as the return type.

0
Jan 29 '14 at 21:18
source share



All Articles