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

Arikon picture Arikon · Oct 27, 2012 · Viewed 29.2k times · Source

I have some code that returns a promise object, e.g. using 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?

Answer

jillro picture jillro · Feb 11, 2014

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> */.