program story

JSDoc에서 약속의 해결 및 거부 유형을 지정하는 방법은 무엇입니까?

inputbox 2020. 11. 12. 08:12
반응형

JSDoc에서 약속의 해결 및 거부 유형을 지정하는 방법은 무엇입니까?


예를 들어 NodeJS 용 Q 라이브러리를 사용하여 promise 객체를 반환하는 코드가 있습니다.

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 (token) → {Promise. <Token>} 입니다 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를 만듭니다).

해당 경로로 이동할 필요가없는 경우 이미 언급했듯이 pipe를 사용하여 @param, @property 또는 @return에 대해 여러 유형을 지정할 수 있습니다 |.

귀하의 경우 @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
*/

현재 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() {
    // ...
};

https://github.com/jsdoc3/jsdoc/issues/1197 에서 github 토론을 참조하십시오.


There's also another way of doing this even though it might be DEPRECATED. Emphasis on might since someone says it's deprecated (check the comments to that answer) while others say either one is fine. I'm reporting it anyway for the sake of completeness.

Now, take Promise.all() for example which returns a Promise fulfilled with an array. With the dot notation style it would look like shown below:

{Promise.<Array.<*>>}

It works on JetBrains products (e.g. PhpStorm, WebStorm) and it's also used in the jsforce docs.

At the time of writing when I try to auto-generate some docs with PHPStorm it defaults to this style even though I found poor reference to it.

Anyway 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 the docs I get this:

/**
 * @returns {Promise.<{array1: Array, array2: Array}>}
 */
const test = async () => {
    let array1 = [], array2 = [];

    return {array1, array2};
};

Here is what I like to do (which may be a little overdone):

/**
 * @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 the base promise with a link to some documentation (in this case I am linking to the jQuery one), define your callbacks that will be called when the promise either resolves or fails, then define your specific promise which links back to the callback documentation.

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

참고URL : https://stackoverflow.com/questions/13104411/how-to-specify-resolution-and-rejection-type-of-the-promise-in-jsdoc

반응형