How to specify resolution and rejection type of the promise in JSDoc?
Even if they don't 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 nice TokenConsume(token) → {Promise.<Token>} with a link to your custom Token
type in the doc.
/** * @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> */
.
I tend to define an external type for the 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 of your function documentation what happens to 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');}
Syntax currently supported by 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() { // ...};
Supported in the future?
/** * 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() { // ...};
See github discussion at: https://github.com/jsdoc3/jsdoc/issues/1197