如何在Node.js中创建一个函数
我正在使用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
}
});
如代码所示,我将根据情况从不同的位置调用相同的函数两次,然后利用它的结果。
是否可以声明一个函数,然后从不同的位置调用,然后利用它的结果?
任何帮助都会非常感激,因为我是Node.js的新手
回答如下:如果你试图从函数中获取一个值,它取决于你是在进行同步(一起添加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);
}