【问题标题】:How to Create a function in Node.js如何在 Node.js 中创建函数
【发布时间】:2019-02-20 01:50:02
【问题描述】:

我正在使用 Firebase 函数来创建 API,同时我正在使用 Firebase Firestore 作为我的数据库。

我正在使用 Node.js 来创建程序。

我想知道如何在 Node.js 中创建函数。

我将不止一次调用代码,因为我已经习惯了 Java 并且 Java 具有分子性,在 Node.js 中也可以吗?

这是我的代码

exports.new_user = functions.https.onRequest((req, res) => {
var abc=``;

  if(a=='true')
  {
    abc=Function_A();//Get the results of Function A
  }
  else
  {
    abc=Function_B();//Get the results of Function B
    //Then Call Function A
  }
});

如代码所示,我会根据情况从不同位置调用相同的函数两次,然后利用它的结果。

是否可以声明一个函数,然后从不同的位置调用 if 然后利用它的结果?

非常感谢任何帮助,因为我是 Node.js 的新手

【问题讨论】:

  • 我不确定 Java 标记是否适用于此。
  • @Thomas 我已经把它说成是因为我已经比较了 Java 和 Node.js 的模块化,并且想知道是否有可能在 Node.js 中实现相同的功能。
  • 嗯,是的,但问题都是关于 Node.js - Java 在这里只是一个参考,但没有与之相关的实际问题。
  • @Thomas 谢谢我已经更新了标签:)。

标签: node.js function firebase google-cloud-firestore


【解决方案1】:

如果您只是想从函数中获取一个值,这取决于您是在执行同步(将 2 个数字相加)还是异步(执行 HTTP 调用)

同步:

  let abc = 0;
  if(a=='true')
   {
    abc = Function_A();//Get the results of Function A
   }
  else
   {
    abc = Function_B();//Get the results of Function B
    //Then Call Function A
   }

   function Function_B() {
      return 2+2;
   }

   function Function_A() {
      return 1+1;
   }

异步:

  let abc = 0;
  if(a=='true')
   {
    Function_A(function(result) {
      abc = result;
    });//Get the results of Function A
   }
  else
   {
    Function_A(function(result) {
      abc = result;
    });//Get the results of Function A

   }

   function Function_B(callback) {
      callback(2+2);
   }

   function Function_A(callback) {
      callback(1+1);
   }

与变量异步:

    let abc = 0;
    Function_A(2, function(result) {
      abc = result;  //should by 4
    });//Get the results of Function A

    function Function_A(myVar, callback) {
      callback(myVar * 2);
    }

【讨论】:

  • 感谢您的回答。我实际上不想将函数分配给变量,而是想将函数返回的值分配给变量。你能帮我解决这个问题吗?如果你能展示如何声明一个将返回值的函数以及如何将该值分配给一个真正有用的函数。
  • 你能帮我让异步函数接受一个将在该函数内部使用的变量值吗?此外,我还创建了一个赏金,并会在 24 小时等待期后奖励您,为您提供非常好的和完整的答案。
猜你喜欢
  • 2023-03-26
  • 2011-02-22
  • 2019-12-29
  • 2015-11-18
  • 1970-01-01
  • 2014-07-08
  • 2022-08-16
  • 2019-05-07
相关资源
最近更新 更多