15

Given this code :

function asyncFoo() {
  return new Promise(function (fulfill, reject) {
    doAsyncStuff(function(err, data) {
      if(err) reject(new Error(err));
      else fulfill(new Bar(data));
    });
  });
}

How can I document that asyncFoo will return a Promise that, when fulfilled will yield an instance of Bar, and when rejected will yield an instance of Error?

/**
 * @return << Here, what do I have to write? >>
 */
function asyncFoo() { ... }
Jens
  • 8,423
  • 9
  • 58
  • 78
DarkChipolata
  • 925
  • 1
  • 10
  • 29
  • > Similar question to https://stackoverflow.com/questions/13104411/how-to-specify-resolution-and-rejection-type-of-the-promise-in-jsdoc/46733261#46733261 – holmberd Oct 13 '17 at 15:28

3 Answers3

28

Looks like you should do the following, based on some other source code's comments.

/**
 * @return {Promise.<Bar>}
 */

How JavaScript Promises are documented.

Similar question with a similar answer. Note the lack of a dot in that answer.

Community
  • 1
  • 1
Ethan B Martin
  • 384
  • 4
  • 3
13

I like to specify that it's an async function with @async and specify the fulfilled return with @returns and error with @throws

/**
 * @async
 * @returns {Bar}
 * @throws {Error}
 */
function asyncFoo() { ... }
  • 1
    Should be an accepted answer. Works like a charm. Only by this way result is correctly recognized by IDE when return value is defined as Interface in the TypeScript file (just for neat autocomplete). – Miraage Aug 28 '17 at 17:45
  • 1
    and yet, the fn doesn't return `{Bar}` nor does it throw `{Error}` – Mr5o1 Sep 15 '17 at 10:18
  • 2
    Nor is the function defined as `async function` [Use JSDoc: @async](http://usejsdoc.org/tags-async.html) – therealklanni Jun 28 '18 at 22:24
  • JSDoc's manual does not recommend this for Promises in general such as the OP's `asyncFoo`: only for functions defined with `async` keyword. _"The @async tag indicates that a function is asynchronous, meaning that it was declared using the syntax async function foo() {}. Do not use this tag for other types of asynchronous functions, such as functions that provide a callback."_ https://jsdoc.app/tags-async.html – dcorking Aug 07 '19 at 10:48
  • 1
    This should be the way to document it. Arguable a function can be considered `async` if it can be invoked with the `await` keyword. The `@async` annotation is needed for functions not declared with the `async` keyword but do return a promise. – Tobbe Brolin Feb 06 '20 at 11:28
0

I personally prefer strict differentiation - declare final type from async function and Promise from a function that directly returns Promise.

/**
  Async JSON request
  @param {string} sql
  @returns {object}
*/
async function request(sql)
{
  return JSON.parse(await dbEngine.executeRequest(sql));
}

/**
  Async JSON request
  @param {string} sql
  @returns {Promise<string>}
*/
function request(sql)
{
  return dbEngine.executeRequest(sql);
}