如何在 JsDoc 中记录返回的数据

How to document returned data in JsDoc

如何记录向服务器请求返回的 JSON 结果?

示例

/**
 * Gets a user's data
 * @returns {jQuery}
 */
function getUserData(userId){
   return $.get('/usr/' + userId);
}

在上面的示例中,返回的数据将是 JSON 的对象,例如

{
   "name" : "Bob",
   "status" : 2
}
/**
 * Gets a user's data request
 * @return {jQuery.jqXHR}
 */
function getUserData(userId){
   return $.getJSON('/usr/' + userId);
}

/*
 * Handles the result of a user data request.
 * @param {Object} data The JSON object, already converted to an Object.
 */
function doSomethingWithUserData(data) {
  console.log('do something with user data:', data);
}

getUserData(userId).done(handleUserData);

正如 Felix 指出的那样,return 值不是 JSON,它甚至不是对象。

引用 JQuery's types documentation:

As of jQuery 1.5, the $.ajax() method returns the jqXHR object, which is a superset of the XMLHTTPRequest object. For more information, see the jqXHR section of the $.ajax entry

因为$.get$.getJSON都是$.ajax的缩写,所以同理。

在示例中,我使用了承诺和处理程序。我从处理程序中创建了一个函数,因此可以更清楚地记录它,但这通常是通过匿名函数完成的。

我还将 $.get 转换为 $.getJSON,这将为您执行 JSON.parse 调用(将回复从字符串转换为对象)。 $.get 的处理程序将采用 @param {string}

更新

在评论中,OP 询问如何使用自定义数据处理此问题,以便未来的开发人员知道在通话中会发生什么。

现在我们已经有了数据,让我们看看如何记录它。

有 3 个很好的文档解决方案,具体取决于复杂程度以及您是否需要进行初始化。

最简单的方法是使用@属性 创建一个@typedef 来描述属性,这不需要额外的代码,并且是纯粹的文档。

goog.provide('UserData');
/* 
 * UserData (in the style of Closure's JSDocs)
 * @typedef {{
 *   name: {string},
 *   title: {string}
 * }}
 */
UserData;

/* 
 * UserData (in the style of useJSDocs)
 * @typedef {Object}
 * @property {string} name
 * @property {string} title
 */
var UserData;

正在使用:

/*
 * Handles the result of a user data request.
 * @param {UserData} data The JSON object, already converted to an Object,
 * cast to UserData
 */
function doSomethingWithUserData(data) {
  console.log('do something with user data:', data);
}

@interface @record相似,可能对你更有用。

最后有一个直接向上 class,如果你能收集更多的默认设置/初始化行并将其放在 class 中,你会 let user = new UserData(jsonUser) ], 这就是我建议的方式。