How to Create a function in Node.js

2019-08-19 01:00发布

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

I am using Node.js to create the program.

I wanted to know how to create a function in 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?

This is my code

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?

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

1条回答
劫难
2楼-- · 2019-08-19 01:44

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)

synchronous:

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

asynchronous:

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

Asynchronous with variable:

    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);
    }
查看更多
登录 后发表回答