Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 512
Arikon Avatar asked Oct 27 '12 21:10

Arikon


People also ask

How do you write resolve and reject a Promise?

Here is an example of a promise that will be resolved ( fulfilled state) with the value I am done immediately. let promise = new Promise(function(resolve, reject) { resolve("I am done"); }); The promise below will be rejected ( rejected state) with the error message Something is not right! .

What is Promise resolve and Promise reject?

Promise.reject(reason) Returns a new Promise object that is rejected with the given reason. Promise.resolve(value) Returns a new Promise object that is resolved with the given value.

What is the type of resolve in Promise?

The Promise. resolve() method "resolves" a given value to a Promise . If the value is a promise, that promise is returned; if the value is a thenable, Promise. resolve() will call the then() method with two callbacks it prepared; otherwise the returned promise will be fulfilled with the value.

How do I resolve Promise results?

Promise resolve() method:If the value is a promise then promise is returned. If the value has a “then” attached to the promise, then the returned promise will follow that “then” to till the final state. The promise fulfilled with its value will be returned.


1 Answers

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

like image 172
jillro Avatar answered Sep 18 '22 02:09

jillro