0

Hi I am calling a function get_location_tcount(1); whose declaration is like

function get_location_tcount(id,callback) {
myDB.transaction(function (transaction) {
    var t_sql = 'select * from tbl_locations where location_structure_id = "' + id+ '"';
    transaction.executeSql(t_sql, [], function (tx, results) {
        var length = results.rows.length;
        callback(length);
    }, null);
});
}

This how I am calling it

var t_count = 0;
get_location_tcount(1,function(total_count){
    alert(total_count); // Alerting the value
    t_count = total_count; // but not setting in variable t_count
});

How to get the desired output

  • @Ivar I think its related to this link you provided but i dont know how to do this with my current code as I haven't worked more with JS – karan singh chauhan Jan 05 '21 at 08:48
  • 1
    Your issue is that the functions you are passing to both `myDB.transaction` and `transaction.executeSql` are called asynchronous. That means that your code continues to run and thus returns `length` _before_ `length = results.rows.length` is executed. You can't simply synchronize code, so you'll need to handle the callback properly. This also includes changes to where ever you are calling `get_location_tcount` from, which you haven't shown here. – Ivar Jan 05 '21 at 08:53
  • This is fundamental on how JavaScript works, so I'd recommend to try to understand that post, both to fix your problem and to get a better understanding of JavaScript so you don't have to encounter these issues again in the future. – Ivar Jan 05 '21 at 08:54
  • Thank You @Ivar , thanks for elaborating the cause to me. I will go through the post you shared. – karan singh chauhan Jan 05 '21 at 08:58

1 Answers1

0

You can pass a callback function as a parameter to get_location_tcount and call that callback function when you have the length. Also make sure to call your callback function if the db call fails.

function get_location_tcount(id, callback) {
myDB.transaction(function (transaction) {
    var t_sql = 'select * from tbl_locations where location_structure_id = "' + id + '" and location_house_id!= "0"';
    transaction.executeSql(t_sql, [], function (tx, results) {
        var length = results.rows.length; // till here length variable getting value
       callback(length);
    }, null);
});
}

// somewhere else in your code
get_location_tcount(2, function(result) {
  console.log(result); //should be your length
}

I agree with Ivar here that you should read up on asynchronous calls. You can use Promise or async/await instead of callback functions.