Node.js 如何在NodeJS中调用函数

Node.js 如何在NodeJS中调用函数,node.js,Node.js,我已经将mysql.js中的函数返回为: function myFunction(resourceIdentifiers,callback){ dbconnection.execute( function(err,response) { response.query('call SP_ExposePricingDetailforUI(' + resourceIdentifiers + ')'

我已经将mysql.js中的函数返回为:

function myFunction(resourceIdentifiers,callback){

    dbconnection.execute( function(err,response) {

        response.query('call SP_ExposePricingDetailforUI(' 
                                      + resourceIdentifiers + ')'
                      ,function (err, rows, fields) {
                          console.log(rows);
                      });
                 }
        );
        return rows;            
}
并尝试在另一个脚本文件restservice.js中将其调用为:

mysql.myFunction(resourceIdentifiers , function(err,rows) {
    console.log(rows);
}

但是由于函数myFunction未定义,我得到了错误。

如果
mysql.myFunction
未定义的
,那么您可能没有实际导出它:

function myFunction(resourceIdentifiers, callback){
    // ...
}

exports.myFunction = myFunction;
默认情况下,函数和变量声明对模块是“私有”的。只有那些明确导出的成员才能从其他模块访问


您也将无法使用
返回行正如您所尝试的那样。异步代码是事件驱动的,不等待,而
return
需要它来执行

myFunction
已经有一个
callback
参数,您正在为该值传递一个
函数。你只需要称之为:

// ...
function (err, rows, fields) {
    callback(err, rows);
}
// ...

您还应该至少在连接时这样做

但是,通常更好的方法是使用占位符(
)和可选的第二个参数
.query()


您只需要在response.query的结果中回调。像这样的

mysql.js:

function myFunction(resourceIdentifiers,callback){

    dbconnection.execute( function(err,response) {

        response.query('call SP_ExposePricingDetailforUI(' 
                                      + resourceIdentifiers + ')'
                      ,function (err, rows, fields) {
                          callback(err, { rows: rows, fields: fields});
                      });
                 }
        );
}

module.exports.myFunction = myFunction;
restservice.js:

mysql.myFunction(resourceIdentifiers , function(err,resp) {
    console.log(resp.rows);
}

更新-删除了我第一次错过的return rows语句。

是否导出myFunction?i、 e:module.exports.myFunction=myFunction;实际上,我需要将结果作为restservice.js而不是mysql.js的响应发送到api调用。请给我一个解决方案谢谢。但当我运行上面的脚本时,我从response.query回调中得到的行不是definedTry console.log(行)。那里记录了什么?@Prem-我不小心在代码中留下了returnrows语句。这是否消除了行未定义的错误?
mysql.myFunction(resourceIdentifiers , function(err,resp) {
    console.log(resp.rows);
}