Q:

Returning an array from function in nodejs

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??

A:

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

