如何在Node.js中创建函数 [英] How to Create a function in Node.js

查看:59
本文介绍了如何在Node.js中创建函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Firebase函数创建API,同时我将Firebase Firestore用作数据库.

I am using Firebase function to create an API and at the same time I Am using the Firebase Firestore as my database.

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

I am using Node.js to create the program.

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

I wanted to know how to create a function in Node.js.

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

I will be calling a code more than once and since I have been use to Java and Java has molecularity will it be possible in Node.js also?

这是我的代码

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
  }
});

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

As shown in the code I would be calling the same function two times from different location depending upon the situation and then utilizing the result of it.

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

Is it possible to declare a function and then call if from different locations and then utilize its result?

当我不熟悉Node.js时,任何帮助将不胜感激

Any help would be really appreciated as I am new to Node.js

推荐答案

如果您试图从函数中获取一个值,则取决于您是同步(将2个数字加在一起)还是异步(进行HTTP调用))

If you are trying to just get a value back from the function it depends if you are doing synchronous (adding 2 numbers together) or asynchronous (doing an HTTP call)

同步:

  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);
    }

这篇关于如何在Node.js中创建函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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