【问题标题】:Describe and hint what parameters a function requires描述并提示函数需要哪些参数
【发布时间】:2020-08-31 09:24:31
【问题描述】:

如何描述我的函数需要哪些参数并在我键入代码时使其可见?

  • 例如,假设我想提示回调函数将采用哪些参数。如果我们看一下下面的 ExpressJS 渲染函数,它会准确显示回调接受和返回的内容。
  • 尽管这个回调应该返回 2 个参数(错误和数据),但我只说 (cb1: any)。有什么特殊的定义方式吗?

目前,我的产品模型中此功能的代码如下所示。如何定义回调函数以暗示它返回什么?

static findById(id, cb1) {
 fs.readFile("./src/database/products.json", (err, data) => {
   if (err) {
     cb1(err, product);
   } else {
     const products = JSON.parse(data);
     const product = products.find(p => p.id == id);
     cb1(err, product);
   }
 });
};

【问题讨论】:

    标签: javascript node.js express


    【解决方案1】:

    【讨论】:

      【解决方案2】:

      使用:Javascript documentation starndards

      或者你需要使用 Typescript 来定义函数接口:

      static findById(id: number, cb1: (err: {}, product: {}) => void) {
       fs.readFile("./src/database/products.json", (err, data) => {
         if (err) {
           cb1(err, product);
         } else {
           const products = JSON.parse(data);
           const product = products.find(p => p.id == id);
           cb1(err, product);
         }
       });
      };
      

      【讨论】:

        【解决方案3】:

        好的,谢谢大家的帮助!似乎只使用没有 typescript 的 jsdocs 就足够了。我不知道 jsdocs 在 vscode 中是如何工作的。将我的代码更改为下面的代码后,我得到了我想要的。我会更多地玩这个。

        /**
        * Finds a `product` with the given `id` and executes a callback `fn` containing the result.
        * @param {number} id
        * @param {(err : Error, product: string) => void} callback
        */
        static findById(id, callback) {
          fs.readFile("./src/database/products.json", (err, data) => {
            if (err) {
              callback(err, product);
            } else {
              const products = JSON.parse(data);
              const product = products.find(p => p.id == id);
              callback(err, product);
            }
          });
        };
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-12-03
          • 2018-10-22
          • 2021-05-06
          • 2013-03-25
          • 1970-01-01
          • 2014-07-15
          • 1970-01-01
          相关资源
          最近更新 更多