0

I have these 2 functions

Here I get details from sales table

   var getLedgerDetails = function (name, id, res) {
    var response = [];
    var f = '%d %b %Y';
    connection.query("SELECT id,voucher_type,DATE_FORMAT(date,?) as date,amount,voucher_number FROM sales WHERE ledger_name=? and company_id=?", [f, name, id], function (err, result) {
        if (err) {
            console.log(err)
        }
        else {
            if (result.length > 0) {
                var r = JSON.stringify(result, null, 2);
                var row = JSON.parse(r);
                return row[0];
            }
            else {

            }
        }
    })
};

and second is

here i want to access the getLedgerDetails Function

getDetails=function(name,id,res){

            //**returns undefined**
             console.log(getLedgerDetails(name,id,res)); 
             }

but it returns me undefined..It makes the function call but returns no value where i am wrong??

Sparw
  • 2,688
  • 1
  • 15
  • 34
primo
  • 1,340
  • 3
  • 12
  • 40
  • 1
    possible duplicate of https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Arif Khan May 29 '18 at 10:09
  • no im working with nodejs not javascript though i already tried the solution which is there in the link – primo May 29 '18 at 10:15
  • 1
    you need to understand nature of JavaScript, I mean how to handle asynchronous call(callback, promise, async/await) – Arif Khan May 29 '18 at 10:18

2 Answers2

0

Its because your code is asynchronous, you have to return your data in a callback function which will be called only at the end.

You can try something like this :

var getLedgerDetails=function(name,id,res, callback) {
        var response = [];
        var f = '%d %b %Y';
        connection.query("SELECT id,voucher_type,DATE_FORMAT(date,?) as date,amount,voucher_number FROM sales WHERE ledger_name=? and company_id=?", [f, name, id], function (err, result) {
            if (err) {
                callback(err, null);
            }
            else {
                if (result.length > 0) {
                    var r = JSON.stringify(result, null, 2);
                    var row = JSON.parse(r);
                    callback(null, row[0]);
                }
                else {
                    callback(null, null);
                }
            }
        });
    };

And your getDetails function

getDetails=function(name,id,res){

    getLedgerDetails(name, id, res, function(err, row) {
        if (err) {
            console.log(err);
        }
        else {
            console.log(row);
        }
    });
};
Sparw
  • 2,688
  • 1
  • 15
  • 34
  • see i am calling it like this way console.log("hhh"+getLedgerDetails(name,id,res,function(err, row) { if (err) { console.log(err); } else { console.log(row+"row"); } })); **what it gives me on console is this** hhhundefined { id: 'd62dc582-e4db-40a8-9f96-0cb0203c11a3-00003a56', voucher_type: 'Purchase', date: '01 Jul 2017', amount: 63336, voucher_number: '111' } [object Object]row – primo May 29 '18 at 10:27
  • And if you try with my example ? – Sparw May 29 '18 at 10:42
  • i tried your example only..just to differentiate the output on console i added strings – primo May 29 '18 at 10:43
  • Yes but it displays you the row, so there is no error ? – Sparw May 29 '18 at 10:44
  • it is not displaying the rows the rows which are shown there are because i had log in getLedgerDetails functions – primo May 29 '18 at 10:45
  • from callback function it gives [object Object] – primo May 29 '18 at 10:45
  • It displays you "[object Object]row", so if your console.log(row) instead of console.log(row + "row") ? – Sparw May 29 '18 at 10:47
  • try returning r[0] in the callback – Gagan Gupta May 29 '18 at 10:51
  • It displays you the row if you console.log(row) ? – Sparw May 29 '18 at 10:51
  • Can you share what is the response before you parse the data to json object. – Vipul Panth May 29 '18 at 10:58
0

It seems you want your function getLedgerDetails to return data whereas the anonymous function associated with your connection.query function is actually returning your data. Being the asynchronous nature of javascript In your case, you can you can use Promises.

Well, Promises provide us with a cleaner code and handling errors with promises is very easy. Also, promises are better when comes to handling nested callbacks that is one after the another.

For Promise:

var Promise = require('promise');


var getLedgerDetails=function(name,id,res) {

    return new Promise(function (resolve, reject) { 
         var response=[];
         var f='%d %b %Y';
         connection.query("SELECT id,voucher_type,DATE_FORMAT(date,?) 
              as date,amount,voucher_number FROM sales WHERE 
              ledger_name=? and 
              company_id=? ,[f,name,id],function(err,result){
             if(err){
                reject(err);//or any custom error message.
             }else {
                if(result.length>0){
                    var r=JSON.stringify(result,null,2);
                    var row=JSON.parse(r);
                    resolve(row[0]);
                }else{

                }
            }
      });
    }

}

Usage:

getLedgerDetails.then(function(success){
   console.log(success)// your db data.
}).catch(function(error) {
    // error handle    
});
Vipul Panth
  • 5,221
  • 4
  • 16
  • 27