如何在JSDoc中指定解决方案和拒绝类型的承诺? [英] How to specify resolution and rejection type of the promise in JSDoc?

查看:171
本文介绍了如何在JSDoc中指定解决方案和拒绝类型的承诺?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码返回承诺对象,例如使用NodeJS的 Q 库。

  var Q = require('q'); 

/ **
* @returns ???
* /
函数任务(err){
return err? Q.reject(new Error('Some error'))):Q.resolve('Some result');
}

如何使用JSDoc记录这样的返回值?

解决方案

即使JavaScript不存在,我发现JSdoc了解通用类型。



因此,您可以定义自定义类型,然后使用 / * @return Promise< MyType> * / 。以下结果导致了一个很好的 TokenConsume(令牌)→{Promise。& Token>} ,其中包含您自定义的令牌类型的链接。

  / ** 
* @typedef令牌
* @property {bool} valid如果令牌有效。
* @property {string} id绑定到令牌的用户标识。
* /

/ **
*消费一个令牌
* @param {string} token [description]
* @return {Promise< Token> ;}令牌的承诺。
* /
TokenConsume = function(string){
// bla bla
}

它甚至可以与 / * @return Promise< MyType | Error> * / / * @return Promise< MyType,Error> * /


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?

解决方案

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

这篇关于如何在JSDoc中指定解决方案和拒绝类型的承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆