Prem
Prem

Reputation: 5987

How to call the function in node js

I have return the function in mysql.js as :

function myFunction(resourceIdentifiers,callback){

    dbconnection.execute( function(err,response) {

        response.query('call SP_ExposePricingDetailforUI(' 
                                      + resourceIdentifiers + ')'
                      ,function (err, rows, fields) {
                          console.log(rows);
                      });
                 }
        );
        return rows;            
}

And tried to call it at another script file restservice.js as :

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

But I get error as the function myFunction is Undefined.

Upvotes: 0

Views: 1351

Answers (2)

dc5
dc5

Reputation: 12441

You just need to callback within the result of response.query. Something like this.

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

Update - removed the return rows statement that I missed the first time around.

Upvotes: 0

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123453

If mysql.myFunction is undefined, then you're probably not actually exporting it:

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

exports.myFunction = myFunction;

Function and variable declarations are "private" to the module by default. Only those members you explicitly export will be accessible from other modules.


You also won't be able to use return rows; as you're trying to. Asynchronous code is event driven and doesn't wait, which return would need it to do.

myFunction already has a callback argument and you're passing a function for the value. You just need to call it:

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

You should also at least escape resourceIdentifiers when concatenating.

But, generally better is to use a placeholder (?) and the optional, 2nd argument to .query():

response.query(
    'call SP_ExposePricingDetailforUI(?)',
    [ resourceIdentifiers ],
    function (err, rows, fields) {
        callback(err, rows);
    }
);

Upvotes: 1

Related Questions